将此.php转换为ObjC可运行的NSURLSession POST请求?

基本上,我尝试登录到此website called Mistar.我可以使用php来做到这一点:

<form action="https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/Login" method="post">
<input type=text name="Pin">
<input type=password name="Password">
<input type="submit" id="LoginButton">
</form>

因此,php(运行时)可以工作.您使用Pin(20005012)和Password(wildcats)进行身份验证,并返回带有类似{1,User Authenticated}的页面

现在,我想做的是可能使用NSURLSession之类的方法从iPhone应用程序(这样的ObjC)登录网站.

到目前为止,这是我所拥有的,但始终使我无法登录页面:

- (void)loginToMistar {

    //Create POST request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    //Create and send request
    NSURL *url = [NSURL URLWithString:@"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/Login"];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    NSString *postString = [NSString stringWithFormat:@"<input type=text name='Pin'> <input type=password name='Password'> <input type='submit' id='LoginButton'>"];
    NSData * postBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:postBody];

 //   [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    NSString* url=[NSString stringWithFormat:url];

    [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
    {
        // do whatever with the data...and errors
        if ([data length] > 0 && error == nil) {
            NSString *loggedInPage = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(loggedInPage);
        }
        else {
            NSLog(@"error");
        }
    }];

有人可以告诉我代码中的问题在哪里吗?

解决方法:

>通常,您需要指定请求的内容类型(application / x-www-form-urlencoded).
>您要构建请求主体以符合该类型的请求(如cmorrissey所述),例如密码= xxx&密码= yyy.
>您要确保对百分比值xxx和yyy进行转义(因为,​​如果密码包含任何保留字符,如,则密码将无法正确传输).
>您需要指定您的请求是POST请求.因此,请使用该原始NSMutableURLRequest并进行正确配置,然后停用您的NSURLRequest.
>您不希望显示以下内容的行:

NSString* url=[NSString stringWithFormat:url];

>您不必创建操作队列.您可以,但是(a)您所做的事情并不是真的很慢,而且计算量很大; (b)这个完成模块很可能最终想要更新UI,并且您永远不会在后台队列中执行此操作,而只能在主队列中执行.
>由于响应似乎是JSON,因此让我们继续分析该响应(如果可以).

因此,您最终得到如下结果:

- (void)loginToMistarWithPin:(NSString *)pin password:(NSString *)password {

    NSURL *url = [NSURL URLWithString:@"https://mistar.oakland.k12.mi.us/novi/StudentPortal/Home/Login"];

    //Create and send request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-type"];

    NSString *postString = [NSString stringWithFormat:@"Pin=%@&Password=%@",
                            [self percentEscapeString:pin],
                            [self percentEscapeString:password]];
    NSData * postBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:postBody];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         // do whatever with the data...and errors
         if ([data length] > 0 && error == nil) {
             NSError *parseError;
             NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
             if (responseJSON) {
                 // the response was JSON and we successfully decoded it

                 NSLog(@"Response was = %@", responseJSON);
             } else {
                 // the response was not JSON, so let's see what it was so we can diagnose the issue

                 NSString *loggedInPage = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                 NSLog(@"Response was not JSON, it was = %@", loggedInPage);
             }
         }
         else {
             NSLog(@"error: %@", error);
         }
     }];
}

- (NSString *)percentEscapeString:(NSString *)string
{
    NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                 (CFStringRef)string,
                                                                                 (CFStringRef)@" ",
                                                                                 (CFStringRef)@":/?@!$&'()*+,;=",
                                                                                 kCFStringEncodingUTF8));
    return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}

然后可以这样称呼它:

[self loginToMistarWithPin:@"20005012" password:@"wildcats"];
上一篇:每日学习心得:SharePoint 2013 自定义列表项添加Callout菜单项、文档关注、SharePoint服务端对象模型查询


下一篇:mac os x 通过Carbon Process Manager启动应用程序