开发者

HTTP Json requests in Java?

开发者 https://www.devze.com 2023-01-31 08:13 出处:网络
How to make HTTP Json requests in Java? Any library? Under \"HTTP Json request\" I mean make POST with Json objec开发者_高级运维t as data and recieve result as Json.Beyond doing HTTP request itself --

How to make HTTP Json requests in Java? Any library? Under "HTTP Json request" I mean make POST with Json objec开发者_高级运维t as data and recieve result as Json.


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.

So, something like:

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

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.


Use Apache HTTP Client 4 and check out this page for JSON and Java.

0

精彩评论

暂无评论...
验证码 换一张
取 消