HTTP Json requests in Java?

后端 未结 2 1223
谎友^
谎友^ 2020-12-11 01:59

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.

2条回答
  •  自闭症患者
    2020-12-11 02:51

    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.

提交回复
热议问题