使用NSURLSession发布请求登录视图

时间:2016-02-09 16:05:02

标签: objective-c login http-post redmine nsurlsession

我正在尝试拥有ios应用的登录视图, 这是我尝试访问的页面http://demo.redmine.org/login 我尝试使用NSURLConnection,但它不适用于ios 9。 如果我的代码存在问题,请告诉我。

- (IBAction)login:(id)sender {
    NSString *username = @"admin";
    NSString *password = @"admin";
    NSString *post = [NSString stringWithFormat:@"%@%@",username, password];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu" , (unsigned long)[postData length]];
    NSURL *url = [NSURL URLWithString:@"http://172.16.231.19/redmine23/login"];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/JSON" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                            completionHandler:
                                  ^(NSData *data, NSURLResponse *response, NSError *error) {

                                      if (error) {
                                          // Handle error...
                                          return;
                                      }

                                      if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                          NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                          NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                      }

                                      NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                      NSLog(@"Response Body:\n%@\n", body);
                                  }];
    [task resume];

这就是我得到的:

    2016-02-09 04:49:19.336 testLoginApp[9574:1247112] Response HTTP Headers:
{
    "Content-Length" = 1208;
    "Content-Type" = "text/html";
    Date = "Tue, 09 Feb 2016 09:48:44 GMT";
    Server = "Microsoft-IIS/8.5";
    "X-Powered-By" = "ASP.NET";
    "X-Request-Id" = c24707e081ab5a8fbd5d3e0ff701b854;
    "X-Runtime" = "0.126006";
}
2016-02-09 04:49:23.312 testLoginApp[9574:1247112] Response Body:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>500 - Internal server error.</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}
fieldset{padding:0 15px 10px 15px;} 
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;} 
h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;} 
#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;
background-color:#555555;}
#content{margin:0 0 0 2%;position:relative;}
.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
-->
</style>
</head>
<body>
<div id="header"><h1>Server Error</h1></div>
<div id="content">
 <div class="content-container"><fieldset>
  <h2>500 - Internal server error.</h2>
  <h3>There is a problem with the resource you are looking for, and it cannot be displayed.</h3>
 </fieldset></div>
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

这是登录视图的完整代码, 我更改了用户名和密码username =%@&amp; password =%@的字符串,我还更改了Content-Type的值,因为Mr.T建议使用邮递员来测试帖子会话并获取请求的代码

NSString *username = @"admin";
NSString *password = @"admin";
got the format from postman by having a key and a value for the username and password
        NSString *post = [NSString stringWithFormat:@"username=%@&password=%@",username, password];
        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
        NSString *postLength = [NSString stringWithFormat:@"%lu" , (unsigned long)[postData length]];
        NSURL *url = [NSURL URLWithString:@"http://demo.redmine.org/login"];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
 got the value for the Content-Type from postman
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];



        NSURLSession *session = [NSURLSession sharedSession];

        NSURLSessionDataTask *task = [session dataTaskWithRequest:request

                                                completionHandler:
                                      ^(NSData *data, NSURLResponse *response, NSError *error) {

                                          if (error) {
                                              // Handle error...
                                              return;
                                          }

                                          if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                              NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                              NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                          }

                                          NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                          NSLog(@"Response Body:\n%@\n", body);
                                      }];
        [task resume];
        UIWebView* webView = [[UIWebView alloc] initWithFrame:self.view.frame];
        [self.view addSubview:webView];
        [webView loadRequest:request];