虽然我读过很多文章,但我仍然无法解决这个问题。
首先,这是IOS中的连接代码,我尝试通过本地网络中的POST METHOD连接到服务器。 (服务器:CENTOS 5.1,PHP 5.5客户端:MAC OSX 10.10.4,IOS 8.4)
-(void)postTest:(NSString *) account and:(NSString *) password{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://192.168.1.104/test.php"]];
[request setHTTPMethod:@"POST"];
[request addValue:@"postValues" forHTTPHeaderField:@"METHOD"];
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:account forKey:@"account"];
[dictionary setValue:password forKey:@"password"];
NSData *data = [[dictionary copy] JSONValue];
[request setHTTPBody:data]; //set the data as the post body
[request addValue:[NSString stringWithFormat:@"%d",data.length] forHTTPHeaderField:@"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(!connection){
NSLog(@"Connection Failed");
}
}
POST后,此处的代码处理从服务器
发送的收到的JSON数据+(NSDictionary*)dictionaryWithJSONData:(NSData*)data{
NSError *error = nil;
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error){
NSLog(@"%@",error);
return nil;
};
return result;
}
在我的主视图控制器中,这样的简单显示
-(void)requestReturnedData:(NSData *)data{ //activated when data is returned
NSDictionary *dictionary = [NSDictionary dictionaryWithJSONData:data];
NSLog(@"%@",dictionary);
NSLog(@"%@",data);
}
服务器端PHP代码:
if($_POST == null){
$handle = fopen('php://input', 'r');
$rawData = fgets($handle);
$body = json_decode($rawData,true);
$file = fopen("testf.txt","a+");
fwrite($file,$body['account']);
fwrite($file,$body['password']);
fclose($file);
}
else{
$body == $_POST;
}
echo json_encode($body);
}
XCODE显示的错误消息如下:
2015-08-10 23:49:35.170 Client_Test[8878:114989] Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x7f8ff27eaea0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
2015-08-10 23:49:35.170 Client_Test[8878:114989] (null)
2015-08-10 23:49:35.171 Client_Test[8878:114989] <0a3c6874 6d6c206c 616e673d 22656e22 3e0a2020 3c686561 643e0a20 2020203c 7469746c 653e6462 5f746573 743c2f74 69746c65 3e0a2020 3c2f6865 61643e0a 20203c62 6f64793e 0a20203c 2f626f64 793e0a3c 2f68746d 6c3e0a0a>
这里最奇怪的部分是我在我的mac中用localhost服务器测试相同的php代码,它工作正常,XCODE显示完整的JSON数据。
在cent os服务器中,我检查了由php代码创建的文件(testf.txt),数据是正确的。所以主要问题是POST时服务器的响应。
请提出一些建议,非常感谢!