簡體   English   中英

客戶端應如何將JSON數據發送到PHP

[英]How should client send json data to PHP

我已經在服務器端使用了php,並且我的客戶端(一個Java程序)使用json數據作為參數發送了一個發布請求。 我可以接收數據,但是jsonData無法解碼。 我正在發送有效的JSON。 以下是我的客戶程序。

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

和我的hello.php

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

輸出:

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

似乎您的Java應用程序在字符串中添加了斜杠,或者如注釋中所建議,PHP應用程序可能在引號中添加了斜杠,以避免SQL注入。嘗試通過添加使其生效

$data = stripslashes($data);

在json_decode部分上方

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM