【发布时间】:2016-08-10 11:09:43
【问题描述】:
我在 iOS 中的代码:
NSString * some_str = @"{\"one\":\"two\",\"three\":\"four\"}";
NSData *objectData = [some_str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&error];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[manager POST:@"https://exmaple.com/post.php" parameters:json progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"Error: %@", error);
}];
我在后端的代码(PHP):
<?php
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
throw new Exception('Request method must be POST!');
}
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
echo $content;
// $responses = array();
header("Content-type: application/json, charset=utf-8");
// echo json_encode($responses);
$conn->close();
?>
如果我回显 $content,iOS 收到的响应将是一些十六进制数字。即 3c21444f 43545950(json 字符串的十六进制数从尾部到头部由“&”符号连接,即三=四&一=二)。如果我回显 $decoded,它会返回一个空的 json。
如果我尝试解码 Post 请求收到的 json,它会失败。我认为接收到的对象可能是 json_decode 函数的输入。
我应该重写我的 iOS 代码或 PHP 代码还是两者兼而有之?
【问题讨论】:
-
你设置错了这一行: NSString * some_str = @"{\"one\":\"two",\"three\":\"four\"}"; '\' 的原因没有放在两个之后,请检查您的数据。
-
@BhadreshKathiriya 这是一个错字。我会纠正它。谢谢。
-
为什么要通过NSString来构造参数?你执行 NSString => NSData => NSDictionary,
AFHTTPSessionManager将执行 NSDictionary => NSData。 -
我猜你可以用邮递员测试你的 php 代码,这将缩小对 bug 的搜索范围
-
谢谢大家!我自己解决了这个问题!
标签: php ios objective-c json afnetworking-3