Java中的HTTP Json请求?

Java中的HTTP Json请求?,第1张

Java中的HTTP Json请求

除了本身进行HTTP请求(甚至可以仅使用 **java.net.URL.openConnection**
即可完成)之外,您还需要一个JSON库。为了方便地与POJO绑定,我建议使用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 requestRequestObject request = ...; // POJO with getters or public fieldsObjectMapper mapper = new ObjectMapper(); // from org.preahaus.jackson.mapmapper.writevalue(connection.getOutputStream(), request);// and read responseResponseObject response = mapper.readValue(connection.getInputStream(), ResponseObject.class);

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

有更好的方法可以使用现有的rest-client库;但从低层次看,这仅是HTTP连接处理以及与JSON进行数据绑定/从JSON进行数据绑定的问题。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5615329.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-15
下一篇2022-12-15

发表评论

登录后才能评论

评论列表(0条)

    保存