簡體   English   中英

帶有JSON的HTTP POST-錯誤的參數

[英]HTTP POST with json - wrong parameters

我正在嘗試調用一個REST服務,該服務接受帶有兩個參數param1param2的json,如下所示:

[{
"param1": "xxx",
"param2": "xxx"
}]

按照我的代碼調用MY_SERVICE_URL:

HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(MY_SERVICE_URL);        
String json = new String("[{\"param1\": \"" + "param1Value" + "\",\"param2\": \"" + "param2Value" + "\"}]");
request.setEntity(new StringEntity(json));
request.setHeader("Content-Type", "application/json");
request.setHeader("Accept", "application/json");

try {
    HttpResponse response = client.execute(request);
    int responseCode = response.getStatusLine().getStatusCode();
    BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
    String output = rd.readLine();
    System.out.println("Response code: " + responseCode);
    System.out.println("Output: " + output);
} catch(Exception ex) {
    System.out.println("Error");
}

client.getConnectionManager().shutdown();

POST失敗,因為它沒有將第一個參數識別為有效:而不是讀取param1,而是考慮了參數\\“ param1 \\”

感謝任何幫助,謝謝西蒙妮

使用以下代碼段創建JSON,以通過您的webservice / api發布。 希望對您有所幫助。也可以添加以下引用import org.json.simple.JSONObject;

JSONObject item = new JSONObject();
item.put("param1", "testValue1");
item.put("param2", 123);
item.put("param3", "testValue3");

String json = item.toString();

暫無
暫無

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

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