I want to send the input as json
using the HttpURLConnection
in java client and the request will be handled by the Spring MVC library jacksonhaus
to response the output as json
URL url = new URL("http://www.test.com/SpringMVC/rest/service/getEmpDetails");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"name\":\"emp1\",\"add\":\"emp2\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
When i use this code i am getting
HTTP error code : 500
In Spring MVC am using the model Attribute for the input Request. Can anyone help me on this.
Not sure about your controller code are you sending http_created
from controller? should you be looking for HttpURLConnection.HTTP_OK
.
Below code may help you
Controller code:
@RequestMapping(value="/jsonconsumer", method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String consumer(@RequestBody JavaBean javaBean) {
return "created";
}
JavaBean code:
@XmlRootElement
public class JavaBean {
private String name = "";
private String add = "";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAdd() {
return add;
}
public void setAdd(String add) {
this.add = add;
}
@Override
public String toString() {
return "JavaBean {name=[" + name + "], add=[" + add + "]}";
}
}
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.