こんにちは、2 つの異なるクライアントから POST を受信する Symfony2 コントローラーがあります。$.post (JQuery) を使用してデータを送信し、NSURLRequest を使用して Objective C iPhone APP を送信する Web のもの。どちらの場合も、JSON 文字列を生成し、POST 経由で送信します。
クライアントによってリクエストの内容が異なるのはなぜですか? 以下を確認してください。
JQuery アプローチ
$.post(myURL, {hist_id: 15}, function(json){}, "json");
この Request オブジェクトを取得します。
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 が得られます。
Objective 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];
この Request オブジェクトを取得します。
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 になります。
その違いはなぜですか?リクエストの内容が、リクエストと Symfony2 コントローラによって読み取り可能な URL 文字列である場合と、2 つ目の場合では JSON が変換されず、その中の変数を読み取ることができないのはなぜですか?
または、それは通常の方法であり、「誰」が私に電話しているかどうかを確認する必要がjson_decode
あり$request->getContent();
ますか?