如何在Java中使用JSON的http POST?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (73)

我想在Java中使用JSON制作一个简单的HTTPPOST。

假设URL是www.site.com

它的值{"name":"myname","age":"20"}标为'details'

如何创建语法?

提问于
用户回答回答于

使用gson库将Java类转换为JSON对象。

为想要发送的变量创建一个POJO类,如上面的示例所示

{"name":"myname","age":"20"}

class pojo1
{
   String name;
   String age;
   //generate setter and getters
}

一旦在pojo 1类中设置了变量,就可以使用以下代码发送它

String       postUrl       = "www.site.com";// put in your url
Gson         gson          = new Gson();
HttpClient   httpClient    = HttpClientBuilder.create().build();
HttpPost     post          = new HttpPost(postUrl);
StringEntity postingString = new StringEntity(gson.toJson(pojo1));//gson.tojson() converts your pojo to json
post.setEntity(postingString);
post.setHeader("Content-type", "application/json");
HttpResponse  response = httpClient.execute(post);

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;

对于gson来说

import com.google.gson.Gson;
用户回答回答于
  1. 获取ApacheHttpClient,这将使您能够提出所需的请求
  2. 用它创建一个HttpPost请求,并添加标题“application/x-www-form-urlencode”
  3. 创建一个StringEntity,将JSON传递给它
  4. 执行调用

代码 //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(); }

扫码关注云+社区

领取腾讯云代金券