Java中的HTTP Json请求?

Edw*_*d83 12 java post json http httpwebrequest

如何用Java生成HTTP Json请求?任何图书馆?在"HTTP Json请求"下,我的意思是使用Json对象作为数据进行POST,并将结果作为Json接收.

Sta*_*Man 14

除了执行HTTP请求本身 - 即使只使用java.net.URL.openConnection即可完成- 您只需要一个JSON库.为方便与POJO结合,我建议杰克逊.

所以,像:

// First open URL connection (using JDK; similar with other libs)
URL url = new URL("http://somesite.com/requestEndPoint");
URLConnection connection = url.openConnection();
connection.setDoInput(true);  
connection.setDoOutput(true);  
// and other configuration if you want, timeouts etc
// then send JSON request
RequestObject request = ...; // POJO with getters or public fields
ObjectMapper mapper = new ObjectMapper(); // from org.codeahaus.jackson.map
mapper.writeValue(connection.getOutputStream(), request);
// and read response
ResponseObject response = mapper.readValue(connection.getInputStream(), ResponseObject.class);
Run Code Online (Sandbox Code Playgroud)

(显然有更好的错误检查等).

有更好的方法可以使用现有的rest-client库来实现这一点; 但是在低级别,它只是HTTP连接处理和数据绑定到/来自JSON的问题.