我知道有类似的问题,因为我已经阅读了大部分,但仍然遇到了问题。我试图向服务器发送 JSON 数据,但我不认为 JSON 数据被接收到。我不确定我错过了什么。下面是我的代码...
发送数据到服务器的方法。
- (void)saveTrackToCloud
{
NSData *jsonData = [self.track jsonTrackDataForUploadingToCloud]; // Method shown below.
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@", jsonString); // To verify the jsonString.
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:http://www.myDomain.com/myscript.php] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
[postRequest setHTTPMethod:@"POST"];
[postRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[postRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[postRequest setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
[postRequest setHTTPBody:jsonData];
NSURLResponse *response = nil;
NSError *requestError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&requestError];
if (requestError == nil) {
NSString *returnString = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
NSLog(@"returnString: %@", returnString);
} else {
NSLog(@"NSURLConnection sendSynchronousRequest error: %@", requestError);
}
}
方法jsonTrackDataForUploadingToCloud
-(NSData *)jsonTrackDataForUploadingToCloud
{
// NSDictionary for testing.
NSDictionary *trackDictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"firstValue", @"firstKey", @"secondValue", @"secondKey", @"thirdValue", @"thirdKey", nil];
if ([NSJSONSerialization isValidJSONObject:trackDictionary]) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:trackDictionary options:NSJSONWritingPrettyPrinted error:&error];
if (error == nil && jsonData != nil) {
return jsonData;
} else {
NSLog(@"Error creating JSON data: %@", error);
return nil;
}
} else {
NSLog(@"trackDictionary is not a valid JSON object.");
return nil;
}
}
这是我的PHP代码。
<?php
var_dump($_POST);
exit;
?>
我从
NSLog(@"returnString: %@", returnString);
接收到的输出是...returnString: array(0) {
}
saveTrackToCloud
是异步调用的。 - ninefifteen$raw_post_data
和$_POST
有什么区别吗?我似乎在使用其中一个时遇到了问题,详见我的问题说明:http://stackoverflow.com/q/41423343/2373410,请帮忙解答。 - Pangu$ _POST
来处理JSON请求。您必须捕获原始请求并将其解码为json_decode
。 - Rob