2011-12-05 14 views
1

JSONオブジェクトをjavaに含むHTMLPostリクエストを生成しました。これをPHPで解析したいと考えています。PHPでのJSON POSTリクエストの解析

public static String transferJSON(JSONObject j) { 
    HttpClient httpclient= new DefaultHttpClient(); 
    HttpResponse response; 
    HttpPost httppost= new HttpPost(SERVERURL); 
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
    nameValuePairs.add(new BasicNameValuePair("json", j.toString())); 

    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    response = httpclient.execute(httppost); 
} 

とサーバ

<?php 

if ($_SERVER['REQUEST_METHOD'] === 'POST') { 

    // input = "json=%7B%22locations%22%3A%5B%7B%22..." 
    $input = file_get_contents('php://input'); 

    // jsonObj is empty, not working 
    $jsonObj = json_decode($input, true); 

に私はJSONの特殊文字がエンコードされているためであると思います。

json_decodeが空の応答を返す

なぜか?

答えて

4

代わりapplication/jsonエンティティを投稿する、あなたが実際に単一の値のペアをJSON =(エンコードされたJSON)とHTTPフォームエンティティ(application/x-www-form-urlencoded)に掲載されています。

代わりの

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
nameValuePairs.add(new BasicNameValuePair("json", j.toString())); 
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

httppost.setEntity(new StringEntity(j.toString(),"application/json","UTF-8")); 
+2

ありがとう、より良い解決策は、入力を変換するよりも。 3つの文字列を持つコンストラクタは存在しません。私は 'StringEntity stringEntity = new StringEntity(j.toString()、" UTF-8 ")を使用しました。 stringEntity.setContentType( "application/json"); ' –

+0

使用しているHTTPクライアント/ HTTPコンポーネントのバージョンとの違いは間違いありません。私はちょうど[最新のjavadoc](http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/entity/StringEntity.html)からコンストラクタを引っ張った – Charlie

+0

それはあるはずです。私はAndroid版Java版を使用しています。 –

2

これは設計上のものです。生のPOSTデータにアクセスしています。このデータはURLエンコードされている必要があります。

データの最初にurldecode()を使用してください。

+0

を試してみて、それが動作するクール!ありがとう –

1

はこれを試してみてください:

//remove json= 
$input = substr($input, 5); 

//decode the url encoding 
$input = urldecode($input); 

$jsonObj = json_decode($input, true); 
関連する問題