dopnpoh056622 2013-04-12 08:39
浏览 48
已采纳

objective-c json php

I'm looking to call a HTTP_POST from the iPhone SDK to a php file on my server. If I call this below:

 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://*****/api2/index.php"]];

[request setHTTPMethod:@"POST"];
[request addValue:@"postValues" forHTTPHeaderField:@"METHOD"];

//create data that will be sent in the post
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:@2 forKey:@"value1"];
[dictionary setValue:@"This was sent from ios to server" forKey:@"value2"];

//serialize the dictionary data as json
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");
}

php code on server

if ($_SERVER['HTTP_METHOD'] == 'postValues'){ 
$body = $_POST; 
$id;// value1 from dictionary 
$name; // value2 from dictionary
}

Please help with $id and $name

  • 写回答

2条回答 默认 最新

  • duanhuai7532 2013-04-12 09:16
    关注

    First, the method of this request is POST, not postValues. All you did is add a header with the name METHOD and the value postValues, so, if you want to check for that, you need to look into the interface between whatever server you're using and PHP. For Apache, that's apache_request_headers().

    Then, if you're setting the JSON object to be the body of the request, then you need to read the body to get to it. To do that, you need to read php://input. So, your example becomes:

    $body = json_decode(file_get_contents('php://input'), true);
    $id = $body['value1'];// value1 from dictionary 
    $name = $body['value2']; // value2 from dictionary
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置