Java中的HTTP Json请求? [英] HTTP Json requests in Java?
问题描述
如何用Java生成HTTP Json请求?任何图书馆?在HTTP Json请求下,我的意思是使用Json对象作为数据进行POST,并将结果作为Json接收。
How to make HTTP Json requests in Java? Any library? Under "HTTP Json request" I mean make POST with Json object as data and recieve result as Json.
推荐答案
超出HTTP请求本身 - 即使只使用 java.net.URL.openConnection 也可以完成 - 你只需要一个JSON库。为方便与POJO的绑定,我建议 Jackson 。
Beyond doing HTTP request itself -- which can be done even just by using java.net.URL.openConnection -- you just need a JSON library. For convenient binding to/from POJOs I would recommend 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);
(显然有更好的错误检查等)。
(obviously with better error checking etc).
使用现有的rest-client库有更好的方法可以做到这一点;但是在低级别,它只是HTTP连接处理和数据绑定到JSON的问题。
There are better ways to do this using existing rest-client libraries; but at low-level it's just question of HTTP connection handling, and data binding to/from JSON.
这篇关于Java中的HTTP Json请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!