您好,我有一个 Symfony2 控制器从两个不同的客户端接收 POST。一个 Web 应用程序,它使用 $.post (JQuery) 和一个使用 NSURLRequest 的 Objective C iPhone APP 发送数据。在这两种情况下,我都会生成一个 JSON 字符串并通过 POST 发送它。
为什么我会根据客户端获得不同的请求内容?检查以下内容:
jQuery 方法
$.post(myURL, {hist_id: 15}, function(json){}, "json");
获取此请求对象:
POST /~pgbonino/Symfony/web/app.php/api/saveTest HTTP/1.1
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate
Accept-Language: es-es
Connection: keep-alive
Content-Length: 17053
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Cookie: PHPSESSID=9l9tkkcm1via94rclfshbajvj5
Host: 127.0.0.1
Origin: http://127.0.0.1
Referer: http://127.0.0.1/~pgbonino/Symfony/web/app.php/dotest/9?t=5400&c=1&w=33&m=e&o=h&save_configuration=false
Surrogate-Capability: symfony2="ESI/1.0"
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/536.30.1 (KHTML, like Gecko) Version/6.0.5 Safari/536.30.1
X-Php-Ob-Level: 1
X-Requested-With: XMLHttpRequest
hist_id=15 [] [] // <-- Take a look at the content of the Request. Here I get an URL style string!!
在这种情况下,当我在 Symfony 控制器中进行操作时,$this->getRequest()->get('hist_id')
我得到了完美的 15。
目标 C 方法
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys: [NSString stringWithFormat: @"%d", 15], @"hist_id"];
NSData* requestData = [NSJSONSerialization myDict options:nil error:&error];
NSLog(@"JSON string:%@", [[NSString alloc] initWithData:requestData encoding:NSUTF8StringEncoding]); // To check that the conversion to JSON is indeed being performed perfectly!!
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"XMLHttpRequest" forHTTPHeaderField:@"X-Requested-With"];
[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=5l272k3858k96s3giajugslv76
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":"0"} [] [] // <-- Take a look at the content of the Request. Here I get a JSON plain text!!
在这种情况下,当我在 Symfony 控制器中执行操作时,$this->getRequest()->get('hist_id')
我得到了 null。
为什么会有这样的区别?为什么请求的内容在一种情况下是 Request 和 Symfony2 控制器可读的 URL 字符串,而在第二种情况下 JSON 没有被转换并且我无法读取其中的变量?
json_decode
或者这是正常的方式,我必须检查“谁”在叫我做$request->getContent();
什么?