在Java中使用JSON进行HTTP POST
假设网址是 www.site.com
并采用{"name":"myname","age":"20"}
标记'details'
为例如的值。
我将如何为POST创建语法?
我似乎也无法在JSON Javadocs中找到POST方法。
回答:
这是你需要做的:
- 获取Apache HttpClient,这将使你能够发出所需的请求
- 使用它创建一个HttpPost请求,并添加标题“ application / x-www-form-urlencoded”
- 创建一个StringEntity,将JSON传递给它
- 执行通话
代码大致看起来像(你仍然需要对其进行调试并使之正常工作)
//Deprecated//HttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
//handle response here...
}catch (Exception ex) {
//handle exception here
} finally {
//Deprecated
//httpClient.getConnectionManager().shutdown();
}
以上是 在Java中使用JSON进行HTTP POST 的全部内容, 来源链接: utcz.com/qa/403815.html