【发布时间】:2013-06-17 13:29:14
【问题描述】:
我有一个 Objective C 项目,我需要将 JSON 数据发送到 Symfony2 php 服务器。
这很正常,我在 Stackoverflow 中阅读了很多文档和以前的问题,我认为我的代码是正确的。但由于某种原因,我没有像我认为的那样在服务器中获取数据。
让我向您展示两个不同版本的代码和结果(在这两个示例中,NSMutableURLRequest *request 变量应该被很好地声明:
设置所有http标题后,我这样做:
NSString *postString = [NSString stringWithFormat:@"hist_id=%d", 10];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
并且一旦发送到服务器,完整的Request值如下:
POST /~pgbonino/Symfony/web/app.php/api/apiGetQuestions HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-us
Connection: keep-alive
Content-Length: 10
Content-Type: application/x-www-form-urlencoded
Cookie: PHPSESSID=8915n9cj4ak8fjna4emvnrsov5
Host: 127.0.0.1
Surrogate-Capability: symfony2="ESI/1.0"
User-Agent: PreparaTest/1.0 CFNetwork/609.1.4 Darwin/12.4.0
X-Php-Ob-Level: 1
hist_id=10 [] [] // <-- TAKE A LOOK AT THE BODY CONTENT
如果我在 PHP $hist_id = $this->getRequest()->get('hist_id') 中这样做,我会正确获得 10。
到目前为止一切都完美!
但是如果我需要向服务器发送一组更复杂的数据怎么办。例如一个 NSDictionary,例如,它的值中有一些数组。在这种情况下,最好使用 JSON,是吗?
这是第二种情况的代码和结果。请注意,在第二个示例中,我不会使用字典和数组,而只是使用具有相同 'hist_id' 值的简单字典。所以我们可以并行化这两个例子。
// Create an array with a dictionary with a unique "hist_id" value set to 10
// (just like before, but using a dictionary and converting it to JSON.
NSDictionary *postDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"%d", 10], @"hist_id",
nil];
// Convert it to json string
NSString *json = [postDictionary JSONRepresentation]; // This is perfectly performed!
// Convert to NSData the json with the dictionary
NSData *requestData = [NSData dataWithBytes:[json UTF8String] length:[json length]];
// Set headers and the body to the request
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
一旦发送到服务器,不幸的是,我在服务器端没有得到正确的请求:
POST /~pgbonino/Symfony/web/app.php/api/saveTest HTTP/1.1
Accept: application/json
Accept-Encoding: gzip, deflate
Accept-Language: en-us
Connection: keep-alive
Content-Length: 15
Content-Type: application/json
Cookie: PHPSESSID=caihkf98lh8injmdju512fvbc7
Host: 127.0.0.1
Surrogate-Capability: symfony2="ESI/1.0"
User-Agent: PreparaTest/1.0 CFNetwork/609.1.4 Darwin/12.4.0
X-Php-Ob-Level: 1
{"hist_id":"10"} [] [] // <-- TAKE A LOOK AT THE BODY CONTENT AND COMPARE WITH THE ABOVE EXAMPLE!!
显然没问题,但是当我去$this->getRequest()->get('hist_id')时,我没有得到任何价值。
我唯一能做的就是:
$content = json_decode($request->getContent());
$hist_id = $content->{'hist_id'};
这是正确的方法吗?在通过 JSON 发送所有内容时,是否有可能仅通过 $this->getRequest()->get('hist_id'); 获得“hist_id”值?好的,我可以使用 json_decode,但我宁愿不使用它,因为我的应用程序应该是多通道的,当我从 web (JQuery.post) 发送数据时,内容会自动转换为 php 数据结构.我不想根据“谁”要求提供信息而对 API 使用不同的代码。
【问题讨论】:
标签: php objective-c json http symfony