12

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.

Edward83
  • 6,664
  • 14
  • 74
  • 102
  • 4
    This is the exact same question as http://stackoverflow.com/questions/4474304/http-json-requests-in-c but with java instead of C++. What are you trying to do? You need to show us what you've tried and what isn't working. We're not here to write your code. – Falmarri Dec 17 '10 at 20:26

1 Answers1

14

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.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • I tried this but it doesn't seem to work.... How do you read Json from the destination Servlet? – user_1357 Aug 19 '11 at 05:58
  • mapper.readValue() does it -- reads JSON via InputStream, binds it to date object. How is it not working? – StaxMan Aug 19 '11 at 18:08
  • In this case URL connection is by JDK, which uses synchronous reads, so it has nothing to do with JSON lib. If you really actually need async (many devs assume they need -- most dont), check out async-http-client, it's pretty simple. – StaxMan Mar 30 '12 at 18:32