I'm trying to invoke a REST Service which accepts a json with the two parameters param1 and param2 , as below:
[{
"param1": "xxx",
"param2": "xxx"
}]
Following my code invoking 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\\"
Any help is appreciated Thanks Simone
Use the below snippet to create JSON for posting over your webservice/api. Hope it helps Add the following reference too 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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.