我曾多次使用GET方法,但在当前情况下,我需要使用POST方法来调用Web服务。我已经查阅了许多教程,但仍然无法实现。
路径为"http://vinipost.com/Services/Mobile_Application/wcfService.svc/logIn",参数为"id"和"pass",测试用的电子邮件地址是"shail@gmail.com",密码是"shail"。
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://vinipost.com/Services/Mobile_Application/wcfService.svc/logIn"]];
[httpClient setParameterEncoding:AFFormURLParameterEncoding];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"http://vinipost.com/Services/Mobile_Application/wcfService.svc/logIn" parameters:@{@"id":@"shail@gmail.com",@"pass":@"shail"}];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
self.movies = [JSON objectForKey:@"logInResult"];
NSLog(@"=========%@",self.movies);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
}];
[operation start];
输出
=========(
{
msg = "Server encountered error";
}
)
服务器端的人说它进入了catch块,这就是为什么它打印出“msg = Server encountered error”的原因。
NSURLConnection
应该会更容易,需要了解 HTTP 的一些知识。在我看来,AFNetworking 只是在添加越来越多的抽象层,这并没有使实际任务变得更容易,反而可能更加混乱。可以使用命令行上的curl
工具进行测试:curl -sSv -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d '<your JSON>' http://yourservice/url
。 - CouchDeveloper