我在 AWS EC2 实例上设置了一个简单的 Web 服务器,并编写了一个小的 test.php 文件,如下所示:
<?php
$dict = array("key" => "value", "test" => "Hello world");
echo json_encode($dict);
?>
在我的浏览器中,我可以转到 http://'myInstanceIP'/test.php,我将获得编码的 JSON 响应。我尝试在 iOS 中执行此操作,但出于某种原因,我只能通过 NSURLConnection 而不是通过 AFNetworking 获得成功的响应。这很奇怪,因为如果我输入一些其他 URL 会给我一个 JSON 响应,AFN 代码就可以工作,而不是在我的 URL 上。
我在 viewDidAppear
中调用它只是为了测试:
- (void)viewDidAppear:(BOOL)animated
{
NSString *urlString = @"http://54.183.178.170/test.php";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"%@", (NSDictionary *)responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failed");
}];
[operation start];
}
我不知道这是我的网络服务器还是 AFN 的故障(因为它在 NSURLConnection 上工作)。
更新: 这是我从 AFNetworking 获得的失败代码:
2014-09-02 11:50:11.538 testingAWS[26751:60b] Failed, error: Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0x8c4ce00 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x8d80fa0> { URL: http://54.183.178.170/test.php } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Length" = 34;
"Content-Type" = "text/html";
Date = "Tue, 02 Sep 2014 18:50:09 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.4.7 (Ubuntu)";
"X-Powered-By" = "PHP/5.5.9-1ubuntu4.3";
} }, NSErrorFailingURLKey=http://54.183.178.170/test.php, NSLocalizedDescription=Request failed: unacceptable content-type: text/html, com.alamofire.serialization.response.error.data=<7b226b65 79223a22 76616522 2c227465 7374223a 2248656c 6c6f2077 6f726c64 227d>}
最佳答案
我们可以在这里看到:
Code=-1016 "Request failed: unacceptable content-type: text/html"
你的问题应该是因为这一行而发生的:
operation.responseSerializer = [AFJSONResponseSerializer serializer];
出于某种原因,您的服务器必须返回非 JSON 响应,而您正在使用 JSONResponseSerializer。因此,如果您将服务器返回类型修复为正确的格式,您可能就没问题了。
或者,您可以像这样更改序列化程序类型:
operation.responseSerializer = [AFHTTPResponseSerializer serializer];
如果只是为了测试目的。
关于ios - NSURLConnection 有效,但 AFNetworking 无效(在特定 URL 上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25629990/