繁体   English   中英

Objective-C的JSON PHP的

[英]objective-c json php

我想从iPhone SDK调用HTTP_POST到服务器上的php文件。 如果我在下面这样称呼:

 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代码

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

请帮助$ id和$ name

首先,此请求的方法是POST ,而不是postValues 您所做的只是添加了一个标题 ,名称为METHOD ,值为postValues ,因此,如果要进行检查,则需要查看所使用的任何服务器与PHP之间的接口。 对于Apache, apache_request_headers()

然后,如果将JSON对象设置为请求的主体,则需要读取该主体才能到达请求。 为此,您需要阅读php://input 因此,您的示例变为:

$body = json_decode(file_get_contents('php://input'), true);
$id = $body['value1'];// value1 from dictionary 
$name = $body['value2']; // value2 from dictionary

您可以在查询中发送额外的值(并使用$ _GET进行检索),也可以将值放入json数据中。

同样,将json作为对象检索的正确方法是:

$bodyAsObject = json_decode( file_get_contents('php://input') );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM