NSURLConnection有效,但AFNetworking没有(在特定的URL上)

时间:2014-09-02 18:32:25

标签: ios amazon-web-services nsurlconnection afnetworking

我在AWS EC2实例上设置了一个简单的Web服务器,并编写了一个小的 test.php 文件,如下所示:

<?php
$dict = array("key" => "value", "test" => "Hello world");
echo json_encode($dict);
?>

在我的浏览器中,我可以访问 http://&#39; myInstanceIP&#39; /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];
}

我无法判断它是否是我的网络服务器或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>}

2 个答案:

答案 0 :(得分:8)

我们可以在这里看到:

Code=-1016 "Request failed: unacceptable content-type: text/html"

由于这一行你的问题应该发生:

operation.responseSerializer = [AFJSONResponseSerializer serializer];

由于某种原因,您的服务器必须返回非JSON响应,并且您正在使用JSONResponseSerializer。因此,如果您修复服务器返回类型的格式正确,您可能会没问题。

或者,您可以像这样更改序列化程序类型:

operation.responseSerializer = [AFHTTPResponseSerializer serializer];

如果仅用于测试目的。

答案 1 :(得分:5)

所以事实证明我需要在json_encode()之前将以下行添加到我的PHP中:

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

然后它适用于AFNetworking。