Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP Json requests in Java?

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.

like image 270
Edward83 Avatar asked Dec 17 '10 19:12

Edward83


1 Answers

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.

like image 117
StaxMan Avatar answered Oct 06 '22 15:10

StaxMan