在Java中使用JSON的HTTP POST [英] HTTP POST using JSON in Java

查看:110
本文介绍了在Java中使用JSON的HTTP POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Java中使用JSON进行简单的HTTP POST。

I would like to make a simple HTTP POST using JSON in Java.

假设网址为 www.site.com

并且它取值 {name:myname,age:20} 例如标记为'details'

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.

推荐答案

以下是您需要做的事情:

Here is what you need to do:


  1. 获取Apache HttpClient,这将使您能够发出所需的请求

  2. 使用它创建一个HttpPost请求并添加标题application / x-www-form-urlencoded

  3. 创建一个将JSON传递给它的StringEntity

  4. 执行调用

  1. Get the Apache HttpClient, this would enable you to make the required request
  2. Create an HttpPost request with it and add the header "application/x-www-form-urlencoded"
  3. Create a StringEntity that you will pass JSON to it
  4. 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(); //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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆