ios - AFNetworking 和 POST 请求

标签 ios afnetworking

我在从 AFNetworking 发出 POST 请求时在 error.userInfo 中收到此响应。 谁能告诉我是我遗漏了什么明显的东西还是我的服务器端需要修复什么?

Request Failed with Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Expected content type {( "text/json", "application/json", "text/javascript" )}, got text/html" UserInfo=0x6d7a730 {NSLocalizedRecoverySuggestion=index test, AFNetworkingOperationFailingURLResponseErrorKey=, NSErrorFailingURLKey=http://54.245.14.201/, NSLocalizedDescription=Expected content type {( "text/json", "application/json", "text/javascript" )}, got text/html, AFNetworkingOperationFailingURLRequestErrorKey=http://54.245.14.201/>}, { AFNetworkingOperationFailingURLRequestErrorKey = "http://54.245.14.201/>"; AFNetworkingOperationFailingURLResponseErrorKey = ""; NSErrorFailingURLKey = "http://54.245.14.201/"; NSLocalizedDescription = "Expected content type {(\n \"text/json\",\n \"application/json\",\n
\"text/javascript\"\n)}, got text/html"; NSLocalizedRecoverySuggestion = "index test"; }

我正在使用这段代码;

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient setDefaultHeader:@"Accept" value:@"application/json"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                        @"Ans", @"name",
                        @"29", @"age",
                        nil];

NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"/" parameters:params];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSLog(@"Success");
        NSLog(@"%@",JSON);

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
        NSLog(@"Failure");
}];

[operation start];
[operation waitUntilFinished];

最佳答案

默认情况下,AFJSONRequestOperation 仅接受来自服务器的“text/json”、“application/json”或“text/javascript”内容类型,但您得到的是“text/html”。

在服务器上修复会更好,但您也可以在您的应用中添加可接受的“text/html”内容类型:

[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];

它对我有用,希望对您有所帮助!

关于ios - AFNetworking 和 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12447725/

相关文章:

ios - 分页UIScrollView如何添加多个UIImageView?

ios - 如何在image.xcassets中使用LaunchImage设置ios launchscreen.xib

ios - 从库中上传视频 Afnetworking multipart

ios7 - IOSLinkedInAPI : Can't share post with the LinkedIn API

ios - 在 Swift 中写入的 JSON 中的顶级类型无效

ios - AFNetworking 预期读取的字节为 -1

ios - 侧边菜单隐藏问题

ios - 在 Swift Messagekit 应用程序中未检测到点击事件?

objective-c - 核心数据、iVar 和类别

ios - AFNetworking 2.0 是否支持后台任务? - IOS 7