Java中的HTTP Json请求?

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

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

所以,像:

// 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); 

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

有更好的方法可以使用现有的rest-client库来完成此任务; 但在低级别,它只是HTTP连接处理和数据绑定到/来自JSON的问题。

使用Apache HTTP Client 4并查看此页面以获取JSON和Java 。