0

我想json使用HttpURLConnectionin java 客户端发送输入,并且请求将由 Spring MVC 库处理jacksonhaus以将输出响应为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());
}

当我使用此代码时,我得到

HTTP错误代码:500

在 Spring MVC 中,我使用模型属性作为输入请求。谁可以帮我这个事。

4

1 回答 1

0

不确定您的控制器代码是http_created从控制器发送的吗?你应该在寻找HttpURLConnection.HTTP_OK.

下面的代码可以帮助你

控制器代码:

@RequestMapping(value="/jsonconsumer", method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String consumer(@RequestBody JavaBean javaBean) {
    return "created";
}

JavaBean 代码:

@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 + "]}";
    }
}
于 2013-04-26T07:40:36.533 回答