在 Java 中使用 JSON 的 HTTP POST

2022-08-31 05:58:30

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

假设网址是www.site.com

例如,它采用标记为的值。{"name":"myname","age":"20"}'details'

如何为 POST 创建语法?

我似乎也无法在JSON Javadocs中找到POST方法。


答案 1

以下是您需要执行的操作:

  1. 获取Apache,这将使您能够发出所需的请求HttpClient
  2. 使用它创建请求并添加标头HttpPostapplication/x-www-form-urlencoded
  3. 创建一个要将 JSON 传递给它的StringEntity
  4. 执行调用

代码大致看起来像这样(您仍然需要调试它并使其工作):

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

答案 2

您可以使用 Gson 库将 java 类转换为 JSON 对象。

按照上面的示例,为要发送的变量创建一个 pojo 类

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

成为

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

一旦你在pojo1类中设置了变量,你可以使用以下代码发送

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;