java - Java 中的 HTTP Json 请求?

标签 java json http post httpwebrequest

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

最佳答案

除了 HTTP 请求本身——这甚至可以通过使用 java.net.URL.openConnection 来完成——你只需要一个 JSON 库。为了方便绑定(bind)到 POJO 或从 POJO 绑定(bind),我建议 Jackson .

所以,像这样:

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

(显然有更好的错误检查等)。

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

关于java - Java 中的 HTTP Json 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4474293/

相关文章:

java - 异常java.lang.IllegalStateException: Activity 已被破坏

json - Cloudformation 列表和字符串::SecurityGroupIds 属性的值必须是字符串列表类型

ios - 保存 JSON 响应以用于调试目的

android - 将 JSON 日期转换为 "mm dd yyyy"格式

java - postgresql hibernate 插入时出现异常

java - 实例化二维数组

c# - 服务器违反了协议(protocol)。 Section=ResponseStatusLine(尝试了很多解决方案都没有用)

docker - 如何对Kubernetes Pod进行动态代理?

python - flask : understanding POST method to transmit data

java - Groovy:如何定义带参数的 java 可调用对象并使其可用于 groovy shell?