在 Java 中使用 JSON 的 HTTP POST [英] HTTP POST using JSON in Java
本文介绍了在 Java 中使用 JSON 的 HTTP POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 Java 中使用 JSON 进行简单的 HTTP POST.
I would like to make a simple HTTP POST using JSON in Java.
假设 URL 是 www.site.com
并且它接受标记为 'details'
的值 {"name":"myname","age":"20"}
例如.
and it takes in the value {"name":"myname","age":"20"}
labeled as 'details'
for example.
我将如何为 POST 创建语法?
How would I go about creating the syntax for the POST?
我似乎也无法在 JSON Javadocs 中找到 POST 方法.
I also can't seem to find a POST method in the JSON Javadocs.
推荐答案
以下是您需要做的:
- 获取 Apache
HttpClient
,这将使您能够发出所需的请求 - 用它创建一个
HttpPost
请求并添加标头application/x-www-form-urlencoded
- 创建一个
StringEntity
,你将把 JSON 传递给它 - 执行调用
- Get the Apache
HttpClient
, this would enable you to make the required request - Create an
HttpPost
request with it and add the headerapplication/x-www-form-urlencoded
- Create a
StringEntity
that you will pass JSON to it - Execute the call
代码大致如下(您仍然需要调试它并使其工作):
The code roughly looks like (you will still need to debug it and make it work):
// @Deprecated HttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params = new StringEntity("details={"name":"xyz","age":"20"} ");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
} catch (Exception ex) {
} finally {
// @Deprecated httpClient.getConnectionManager().shutdown();
}
这篇关于在 Java 中使用 JSON 的 HTTP POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文