2011-12-05 4 views
1

Java에서 JSON 객체를 포함하는 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); 
} 

그리고 서버 내가 JSON 특수 문자 인코딩되기 때문에이 추측

<?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_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에서 자바 버전을 사용하고 있습니다. –

2

의도적으로 설계된 것입니다. URL 인코딩 된 원시 POST 데이터에 액세스하고 있습니다.

데이터에 우선 urldecode()을 사용하십시오.

+0

쿨보십시오! 감사합니다 –

1

이 시도 :

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

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

$jsonObj = json_decode($input, true);