我想通過json格式向服務器端的php文件發送數據數組(字典端),以便稍後將數據存儲到MySQL數據庫。但是,它看起來像由PHP接收的數據對象始終爲空。發送json數據到php返回null
下面是Objective-C的線:
NSURL *url = [NSURL URLWithString:@"http://myaddress/upload.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:self.sentData];
NSError *error = nil;
NSURLResponse *response = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error) NSLog(@"%s: NSURLConnection error: %@", __FUNCTION__, error);
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"responseString: %@",responseString);
下面是PHP行:
<?php
$json_data=file_get_contents('php://input');
$post_data = json_decode($json_data);
if (is_array($post_data))
$response = array("status" => "ok", "code" => 0, "original request" => $post_data);
else
$response = array("status" => "error", "code" => -1, "original_request" => $post_data);
$processed = json_encode($response);
echo $processed;
?>
上xcode中調試消息是如下:
2015-07-19 17:34:35.900 PhpPostTest[1531:557248] responseString: {"status":"error","code":-1,"original_request":null}
貌似連接沒問題,但響應字符串表明php端收到的數據爲空。任何人都可以提出什麼是潛在的問題嗎?
我可以看到您嘗試解碼的JSON嗎? – Hedam
Jep,如果您試圖解析的json無效,json_decode返回null。所以$ json_data可能包含無效的json ...您嘗試解析它,$ post_data變爲null。 – Verkade89