1

I've generate an HTMLPost Request containing a JSON object in java and would like to parse it in PHP.

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);  
}

And on the server

<?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);

I guess this is because the JSON special characters are encoded.

The json_decode return empty response

Any idea why ?

casperOne
  • 72,334
  • 18
  • 180
  • 242
Martin Trigaux
  • 5,221
  • 9
  • 42
  • 58

3 Answers3

4

Instead of POSTing an application/json entity, you are actually posting an HTTP form entity (application/x-www-form-urlencoded) with a single value pair json=(encoded json).

instead of

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

Try

 httppost.setEntity(new StringEntity(j.toString(),"application/json","UTF-8"));
Charlie
  • 7,031
  • 1
  • 37
  • 45
  • 2
    Thanks even better solution than transforming the input. Your constructor with 3 Strings doesn't exists. I used `StringEntity stringEntity = new StringEntity(j.toString(),"UTF-8"); stringEntity.setContentType("application/json");` – Martin Trigaux Dec 05 '11 at 21:21
  • Could definitely be a difference with the version of HTTP Client / HTTP Components you are using. I just pulled the constructor from [the latest javadoc](http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/entity/StringEntity.html) – Charlie Dec 05 '11 at 23:35
  • Ok should be that. I'm using the java version on Android. – Martin Trigaux Dec 06 '11 at 07:34
2

That's by design: you are accessing the raw POST data, which needs to be URLencoded.

Use urldecode() on the data first.

Pekka
  • 431,103
  • 135
  • 960
  • 1,075
1

Try this:

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

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

$jsonObj = json_decode($input, true);
Razvan Pat
  • 21
  • 3