I'm trying to log in to Mistar using NSURLSession (or AFNetworking, or something else, whatever seems appropriate) Heres my code:

- (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:@"Pin=%@&Password=%@", @"20005012", @"wildcats"];
   NSData * postBody = [postString dataUsingEncoding:NSUTF8StringEncoding];
   [request setHTTPBody:postBody];

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

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

   [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");
        }
    }];
}

It logs in, and returns the HTML content of the page saying my login failed. So it succeeds in passing a request, but it fails and gives me the Error with login page instead.

What's wrong with my request?

有帮助吗?

解决方案

Since you are posting data to server you must call this method for your NSMutableURLRequest object-

[urlRequest setHTTPMethod:@"POST"];

The default HTTP method is "GET". Read more-

https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSMutableURLRequest_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableURLRequest/setHTTPMethod:

其他提示

If you use the convenience API of NSURLConnection, sendAsynchronousRequest:queue:completionHandler: and require authentication, you MUST pass the credentials within the URL in some appropriate way. This implies that the server supports this naive authentication method.

In order to have more control over the authentication process, you should use NSURLSession or NSURLConnection using delegates.

See also: sendAsynchronousRequest:queue:completionHandler:

and URL Loading System Programming Guide

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top