2014-05-13 13:56
浏览 46


I have used php for server side and my client(A java program) sends a post request with json data as parameter. I am able to receive the data but the jsonData is no decoding. I am sending a valid JSON. Below is my Client program.

public class ExampleHttpPost
  public static void main(String args[]) throws ClientProtocolException, IOException
    HttpPost httppost = new HttpPost("http://localhost/hello.php");
    List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
    try {
        parameters.add(new BasicNameValuePair("data", (new JSONObject("{\"imei\":\"imei1\"}")).toString()));
    } catch (JSONException e) {
        // TODO Auto-generated catch block
    httppost.setEntity(new UrlEncodedFormEntity(parameters));
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse httpResponse = httpclient.execute(httppost);
    HttpEntity resEntity = httpResponse.getEntity();

    // Get the HTTP Status Code
    int statusCode = httpResponse.getStatusLine().getStatusCode();

    // Get the contents of the response
    InputStream input = resEntity.getContent();
    String responseBody = IOUtils.toString(input);

    // Print the response code and message body
    System.out.println("HTTP Status Code: "+statusCode);

And my hello.php

    $data = $_POST['data'];
$obj = json_decode($data);
    echo "Decoding error";
echo $obj['imei'];

Output :

HTTP Status Code: 200
string(20) "{\"imei\":\"imei1\"}"
Decoding error
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dquoj04882
    dquoj04882 2014-05-13 14:02

    It seems like your Java Application is adding slashes to the string or as suggested in the comments the PHP app is probably adding slashes to the quotes to avoid SQL injection Try if you can get it to work by adding

    $data = stripslashes($data);

    Above the json_decode part

    点赞 评论