挣扎着想出这个。看到很多例子,不知道我在这里做错了什么。需要一些新鲜的眼睛。我有一个数组和一个字典,我试图通过HTTPBody发送,然后返回任何一个,只是为了看到它的工作。这就是我所拥有的:
NSURL *url = [NSURL URLWithString:@"http://..."];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
NSString *postData = [NSString stringWithFormat:@"dictofcorners=%@&arrayofids=%@", dict, _idKeys];
NSString *length = [NSString stringWithFormat:@"%d", postData.length];
[request setValue:length forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:[postData dataUsingEncoding:NSASCIIStringEncoding]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if ([httpResponse statusCode] == 200) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]);
}
}];
服务器端我只想发送回数组或字典。响应为200,数据为空。我如何处理数据服务器端?或者在发送请求之前,我应该做些什么来序列化数组和字典?
<?php
$dictofcorners = json_decode($_REQUEST['dictofcorners']);
echo json_encode($dictofcorners);
//$arrayofids = json_decode($_REQUEST['arrayofids']);
//echo json_encode($arrayofids);
?>
以下答案!
答案 0 :(得分:0)
我是如何让它工作的......显然:
NSMutableDictionary *paramDic = [NSMutableDictionary new];
[paramDic setValue:dic forKeyPath:@"dic"];
[paramDic setValue:_idKeys forKeyPath:@"array"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:paramDic options:NSJSONWritingPrettyPrinted error:nil];
NSURL *url = [NSURL URLWithString:@"http://....php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSString *length = [NSString stringWithFormat:@"%d", jsonData.length];
[request setValue:length forHTTPHeaderField:@"Content-Length"];
[request setValue:@"json" forHTTPHeaderField:@"Data-Type"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if ([httpResponse statusCode] == 200) {
//...
php部分:
$input = file_get_contents("php://input");
$obj = json_decode($input, true);
$dic = $obj['dic'];
$array = $obj['array'];
我不懂php部分,但它有效。基本上只需要创建一个对象来传递身体......所以我创建了一个字典并添加了我需要传递的所有内容。如果有人想解释php部分,php://输入部分,我很乐意听到它!