premeclat premeclat - 8 months ago 39
Java Question

Sending input as json and receiving the ouput as json using java HttpURLConnection and Spring MVC Controller

I want to send the input as

using the
in java client and the request will be handled by the Spring MVC library
to response the output as

URL url = new URL("");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/json");

String input = "{\"name\":\"emp1\",\"add\":\"emp2\"}";

OutputStream os = conn.getOutputStream();

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:

public class JavaBean {

    private String name = "";
    private String add = "";

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public String getAdd() {
        return add;

    public void setAdd(String add) {
        this.add = add;

    public String toString() {
        return "JavaBean {name=[" + name + "], add=[" + add + "]}";