php - AFNetworking JSON请求不起作用

标签 php ios json afnetworking

我正在尝试启动此操作,它甚至没有进入NSLOG。
我猜想它与我的stringUrl有关,也许它不应该像这样工作?

这是我的代码:

NSString *stringUrl = [[NSString alloc]initWithFormat:@"http://example.com/add_user.php?username=%@&password=%@&country=%@&email=%@",[self.usernameTextField text],[self.passwordTextField text], countrySelected, [self.emailTextField text]];

NSURL *url = [NSURL URLWithString:stringUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSDictionary *dict = JSON;
    NSLog(@"IP Address: %@", [JSON valueForKeyPath:@"item"]);
} failure:nil];

[operation start];

编辑:
这是我从故障块中得到的:

Error Domain = AFNetworkingErrorDomain代码= -1016“预期的内容类型{(
“text / json”,
“application / json”,
“文本/ javascript”
)},得到了text / html“UserInfo = 0xa2b4300 {NSLocalizedRecoverySuggestion = {” type“:” 1“,” item“:”用户添加成功。“}
,AFNetworkingOperationFailingURLRequestErrorKey = http://EXAMPLE.com/add_user.php?username = aaasafasfasf&password = aaa&country = Angola&email = aaaasfasfasfasfasf>,NSErrorFailingURLKey = http://EXAMPLE.com/add_user.php?username=aaasafasfasf&password=aaa&country=Angola&email=aaaasfasfasfasfasf,NSLocalizedDescription =预期的内容类型{{
“text / json”,
“application / json”,
“文本/ javascript”
)},有text / html,AFNetworkingOperationFailingURLResponseErrorKey =}

最佳答案

为了进入AFJSONRequestOperation的成功块,您还需要遵守服务器要发送的正确内容类型。当前,您的服务器正在返回text / html内容类型作为响应,因此它进入了故障块。

正如失败阻止消息所暗示的那样,由于您正在使用AFJSONRequestOperation,因此将返回的内容类型更改为text / json或application / json。

对于PHP,您可以按照以下问题的答案来更改返回的内容类型:How to change content type in php?

您可以在现有标题行下方添加另一行:

header('Content-Type: text/json');

除非有标题行将内容类型设置为text / json或application / json以外的其他内容,否则无需替换现有标题行。

关于php - AFNetworking JSON请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17392055/

相关文章:

php - 使用 get 在 php 中检索值

objective-c - UIImage drawInRect : is very slow; is there a faster way?

ios - 使用新的UIImage更新UIImageView

json - Tastypie 反序列化结果在 {"error": ""}

php - 使用 json 从 IMDB 获取数据

php - 无法使用 MySQL 查询检查两列中的值

php - 将 php 变量传递到 WordPress 查询函数中

php - 尝试从数据库 jquery 检索用户名

ios - 只登录调试器,但报告中没有数据

json - 发布引用类型的对象