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 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题