简体   繁体   English

带有JSON的HTTP POST-错误的参数

[英]HTTP POST with json - wrong parameters

I'm trying to invoke a REST Service which accepts a json with the two parameters param1 and param2 , as below: 我正在尝试调用一个REST服务,该服务接受带有两个参数param1param2的json,如下所示:

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

Following my code invoking MY_SERVICE_URL: 按照我的代码调用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();

The POST is failing because it's not recognizing the first parameter as valid: instead of reading param1 it's considering the parameter \\"param1\\" POST失败,因为它没有将第一个参数识别为有效:而不是读取param1,而是考虑了参数\\“ param1 \\”

Any help is appreciated Thanks Simone 感谢任何帮助,谢谢西蒙妮

Use the below snippet to create JSON for posting over your webservice/api. 使用以下代码段创建JSON,以通过您的webservice / api发布。 Hope it helps Add the following reference too import org.json.simple.JSONObject; 希望对您有所帮助。也可以添加以下引用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