Edd*_*e K 2 nsurlconnection amazon-web-services ios afnetworking
我在AWS EC2实例上设置了一个简单的Web服务器,并编写了一个小的test.php文件,如下所示:
<?php
$dict = array("key" => "value", "test" => "Hello world");
echo json_encode($dict);
?>
Run Code Online (Sandbox Code Playgroud)
在我的浏览器中,我可以访问http://'myInstanceIP'/test.php,我将获得编码的JSON响应.我尝试在iOS中执行此操作,出于某种原因,我只能通过NSURLConnection获得成功的响应,而不是通过AFNetworking.这很奇怪,因为如果我输入一些其他会给我一个JSON响应的URL,而不是我的URL,AFN代码就可以工作.
我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];
}
Run Code Online (Sandbox Code Playgroud)
我不知道这是我的网络服务器或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>}
Run Code Online (Sandbox Code Playgroud)
我们可以在这里看到:
Code=-1016 "Request failed: unacceptable content-type: text/html"
Run Code Online (Sandbox Code Playgroud)
由于这条线,您的问题应该发生:
operation.responseSerializer = [AFJSONResponseSerializer serializer];
Run Code Online (Sandbox Code Playgroud)
出于某种原因,您的服务器必须返回非JSON响应,并且您正在使用JSONResponseSerializer.因此,如果您修复服务器返回类型正确的格式,您可能会没问题.
或者,您可以像这样更改序列化程序类型:
operation.responseSerializer = [AFHTTPResponseSerializer serializer];
Run Code Online (Sandbox Code Playgroud)
如果只是为了测试目的.
所以事实证明我需要在我的PHP中添加以下行json_encode():
header('Content-type: application/json');
Run Code Online (Sandbox Code Playgroud)
然后它适用于AFNetworking.
| 归档时间: |
|
| 查看次数: |
5138 次 |
| 最近记录: |