Objective-C POST请求未正确“发布”

时间:2018-12-13 02:55:36

标签: objective-c xcode post

我正在尝试为学校开发一个应用程序,第一步是POST进入我们的成绩册。我的代码如下:

NSString *usernameText = _username.text;
NSString *passwordText = _password.text;
NSString *post = [NSString stringWithFormat:@"username=%@&password=%@",usernameText, passwordText];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
NSURL *url = [NSURL URLWithString:@"(school website, not putting real URL)"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
[_webView loadRequest:request];

问题在于,它“不起作用”。 Web视图已刷新,但是没有输入数据,也没有页面更改。我想知道我做错了什么,是否可能忽略了某些事情。预先感谢

编辑: 我已经尝试过NSURLSession并在响应中得到了这个: (经过审查的网站名称,给出了位置)

2018-12-13 20:07:07.277108-0500 sisParsing[29432:2736415] Error: (null)
2018-12-13 20:07:07.277459-0500 sisParsing[29432:2736415] Response: <NSHTTPURLResponse: 0x6000028ce300> { URL: website } { Status Code: 200, Headers {
"Access-Control-Allow-Origin" =     (
    "*"
);
"Cache-Control" =     (
    "no-cache, no-store"
);
"Content-Length" =     (
    13437
);
"Content-Type" =     (
    "text/html; charset=utf-8"
);
Date =     (
    "Fri, 14 Dec 2018 01:07:29 GMT"
);
Expires =     (
    "-1"
);
Pragma =     (
    "no-cache"
);
Server =     (
    "Microsoft-IIS/8.5"
);
"Set-Cookie" =     (
    "ASP.NET_SessionId=hchdpifc13c3hhrowxnjjzfj; path=/; secure; HttpOnly"
);
"X-AspNet-Version" =     (
    "4.0.30319"
);
"X-Powered-By" =     (
    "ASP.NET"
);
} }

1 个答案:

答案 0 :(得分:0)

在使用POST或GET数据到Web后端时,安装Postman应用程序总是一件很棒的事情(它免费且易于使用)。尝试从Postman发送具有相同数据(用户名和密码)的请求,然后查看Web后端答复的内容。这样,您就可以确定是代码还是后端出了问题。我不隶属于Postman,但我目前也在开发Web应用程序,它是帮助我调试代码的最佳工具。

或者,您也可以尝试通过使用NSURLSession而不使用webview来发送POST请求,并查看返回的回复或应用产生的错误。如下所示:

//before this you need to construct session object with appropriate url and params. (google to see example).

NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
 NSLog("Error: %@", error);
 NSLog("Response: %@", reponse);
}];

[postDataTask resume];

祝你好运!