AfNetworking 2.0 发布问题

3

我最近想在我的iOS应用程序中使用AFNetworking。同一页内容使用ASIHTTPRequest时可以正常响应,但是使用AFNetworking却不能。这是我的尝试。

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *params = @{@"user[height]": @"10",
                             @"user[weight]": @"255"};
    [manager POST:@"http://localhost:8888/TestingPost/post.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

我已经尝试了很多选项,比如在不同的xml / json / html中添加序列化,但都没有用。

在PHP页面上,我并没有做什么花哨的事情,只是将页面上发布的内容打印出来。但问题仍然存在。

<?php
// Show all information, defaults to INFO_ALL

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



print_r($_POST[]);
/*
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$password = $_POST['password'];
*/

//echo( "hurray");

?>

请您详细说明一下。我想从ASIhttprequest切换到更新且更受支持的工具。

这是请求的结果:

Networking_example[1777:41979] Error: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: internal server error (500)" UserInfo=0x7f9feae16d60 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7f9fedb029a0> { URL: http://localhost:8888/TestingPost/post.php } { status code: 500, headers {
    Connection = close;
    "Content-Length" = 0;
    "Content-Type" = "text/html";
    Date = "Thu, 16 Oct 2014 18:08:08 GMT";
    Server = Apache;
    "X-Powered-By" = "PHP/5.5.10";
} }, NSErrorFailingURLKey=http://localhost:8888/TestingPost/post.php, com.alamofire.serialization.response.error.data=<>, NSLocalizedDescription=Request failed: internal server error (500)}

顺便提一下,你的PHP指定了一个JSON头(我认为应该是application/json),但没有返回JSON。要么改成返回JSON,要么更改该头文件(例如application/text)。 - Rob
1个回答

0

如果你的PHP正在使用$_POST,这意味着你可以使用AFHTTPRequestSerializer的默认requestSerializer(即application/x-www-form-urlencoded请求)。

但是你的JSON没有生成JSON响应,因此您需要将responseSerializer更改为AFHTTPResponseSerializer

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

你的PHP页面报告了500错误。这是一个“内部服务器错误”,状态码定义如下:

服务器遇到了意外情况,阻止了它完成请求。

这表明有PHP错误。也许你想要:

print_r($_POST);

通常,与 Web 服务交互时,最好生成 JSON 响应,例如:
echo(json_encode($_POST));

显然,如果你生成JSON响应,你可能也想使用默认的[AFJSONResponseSerializer serializer]设置,而不是将其更改为AFHTTPResponseSerializer


但是对于ASIhttpRequest,同样的页面可以正常工作。如果网页存在问题,则该库也不应该正常工作。我会尝试并相应更新。 - IDev
顺便说一下,您可以使用Charles观察您的ASI请求,并使用AFNetworking重复。这样,您就可以确定两个请求之间的区别了。 - Rob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接