dpwh11290 2014-05-13 13:56
浏览 50
已采纳

客户端应该如何将json数据发送给PHP

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
        e.printStackTrace();
    }
    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);
    input.close();

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

And my hello.php

<?php
    $data = $_POST['data'];
var_dump($data);
$obj = json_decode($data);
if($obj==NULL){
    echo "Decoding error";
}
echo $obj['imei'];
?>

Output :

HTTP Status Code: 200
string(20) "{\"imei\":\"imei1\"}"
Decoding error
  • 写回答

1条回答 默认 最新

  • 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog