I have a springboot project that takes only POST JSON String which I'm converting to HashMap using gson. I tested using Postman as a POST and add the body as props with a json string like {'fistname': 'John', 'lastname' : 'Doe'}, translates to props = {'fistname': 'John', 'lastname' : 'Doe'}. its working as expected
@RequestMapping(value = "/rest", method = RequestMethod.POST)
protected String parse(@RequestParam("props") String props) {
Gson gson = new Gson();
Map<String, String> params = new HashMap<String, String>();
params = gson.fromJson(props, Map.class);
// Rest of the process
}
On the other hand, I have a JavaEE project, which needs to call this API
protected void callREST() {
try {
String json = someClass.getDate() //retrieved from database which is stored as json structure
Map<String, String> props = gson.fromJson(json, Map.class);
URL url = new URL("http://localhost:9090/myApp/rest");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
DataOutputStream wr = new DataOutputStream( conn.getOutputStream());
System.out.println(props.toString());
wr.writeBytes(json.toString());
wr.flush();
wr.close();
if(conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed :: HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
System.out.println("Output from Server ... \n");
while((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch(Exception e) {
//print stack trace
}
}
I get Failed :: HTTP error code : 400. I suspect the spring boot is not receiving the data in props variable since its a POST request.
What should i add in the client code to pass the props and the data to make this call successful ?
Note: JavaEE is running on tomcat :8080, Springboot is running on different tomcat :9090
RestTemplateclass, it is very useful for this.