我在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字符串的十六进制数从尾部开始到由#34连接的头部;&amp;&#34;符号,即三个=四个&amp;一个= 2)。如果我回显$ decode,它会返回一个空的json。
如果我尝试解码Post请求收到的json,则失败。我相信收到的对象是json_decode函数的可能输入。
我应该重写我的iOS代码或PHP代码吗?
答案 0 :(得分:0)
试试这个......可能有帮助
创建方法并将参数传递给该方法
+ (void)apiRequestForPOSTWithServiceName:(NSString *)serviceName andParameters:(NSDictionary *)parameter withCompletion:(void(^)(id response, BOOL isSuccess))completion
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSString *url = [NSString stringWithFormat:@"%@%@", BASE_URL, serviceName];
[manager POST:url parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
//NSLog(@"JSON: %@", responseObject);
completion(responseObject,YES);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
completion(error,NO);
}];
}
...谢谢