如何通过手机sdk中的afnetworking从服务器获取数据

Posted

技术标签:

【中文标题】如何通过手机sdk中的afnetworking从服务器获取数据【英文标题】:how to fetch data from server through afnetworking in phone sdk 【发布时间】:2015-01-29 07:36:51 【问题描述】:

我正在创建 ios 应用程序并尝试通过以下网络代码从服务器获取数据

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://XXXXXX/DisplayDetail.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) 
    if (error) 
        NSLog(@"Error: %@", error);
     else 
        NSLog(@"%@ %@", response, responseObject);
    
];
[dataTask resume];

但我收到以下错误

Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0x7f9f3943aee0 com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7f9f3954e0b0>  URL: http://run2tour.com/bud_api/DisplayDetail.php   status code: 200, headers 
Connection = "Keep-Alive";
"Content-Type" = "text/html";
Date = "Thu, 29 Jan 2015 07:30:36 GMT";
"Keep-Alive" = "timeout=5";
Server = "Apache/2.4.10 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4 mod_fcgid/2.3.10-dev";
"Transfer-Encoding" = Identity;
"X-Powered-By" = "PHP/5.4.34"; 
,
NSErrorFailingURLKey=http://run2tour.com/bud_api/DisplayDetail.php, com.alamofire.serialization.response.error.data=<5b7b2275 7365725f 6964223a 22313039 222c2275 7365725f 656d6169 6c223a22 616e7572 61674067 

............

所以请帮我解决一下。

【问题讨论】:

【参考方案1】:

快速修复 - 在 AFNetworking acceptableContentTypes 字段的 AFJSONResponseSerializer 类中定义。您必须在此处添加text/html 类型。

它是一个 JSON 响应,所以它应该是 text/json。

【讨论】:

【参考方案2】:

从错误消息中,服务器返回的内容类型不正确。服务器确实返回 JSON,但标头显示其 HTML。

你真的应该修复服务器头。

一个糟糕的解决方案是教 AFN 在响应序列化类中将 HTML MIME 类型响应视为 JSON。

【讨论】:

所以请告诉我设置标题的代码是什么 这是服务器返回的标头 - 应用程序代码可能没问题。你/需要设置一个接受标头吗?【参考方案3】:

正如@Wain 所说,最好的方法是更改​​后端的标头

例如在你的http://XXXXXX/DisplayDetail.php"文件中你应该添加

header('Content-type: application/json');

PHP 参考资料 http://www.w3schools.com/php/func_http_header.asp http://php.net/manual/en/function.header.php

【讨论】:

以上是关于如何通过手机sdk中的afnetworking从服务器获取数据的主要内容,如果未能解决你的问题,请参考以下文章

如何通过 AFNetworking API 调用使用 gzip 解压?

如何通过 AFNetworking 创建简单的 Http 请求

如何通过 AFNetworking 传递 facebook 访问令牌

AFNetworking - 如何通过 ID 发出 POST 请求

如何通过 POST 和 AFNetworking 以变量形式发送数据?

如何清除 AFNetworking 中的旧缓存?