Java中的HTTP Json请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4474293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:53:35  来源:igfitidea点击:

HTTP Json requests in Java?

javajsonhttpposthttpwebrequest

提问by Edward83

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.

如何在 Java 中发出 HTTP Json 请求?有图书馆吗?在“HTTP Json 请求”下,我的意思是使用 Json 对象作为数据进行 POST,并以 Json 接收结果。

采纳答案by StaxMan

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 Hymanson.

除了执行 HTTP 请求本身——这甚至可以通过使用java.net.URL.openConnection来完成——你只需要一个 JSON 库。为了方便绑定到/从 POJO,我推荐Hymanson

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.Hymanson.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.

使用现有的 rest-client 库有更好的方法来做到这一点;但在低级别,它只是 HTTP 连接处理和数据绑定到/从 JSON 的问题。