如何使用Apache HTTP客户端将复杂参数传递给POST请求?

问题描述 投票:1回答:2

我试图用这样的正文发送POST请求

{
  "method": "getAreas",
  "methodProperties": {
      "prop1" : "value1",
      "prop2" : "value2",
   }
}

这是我的代码

static final String HOST = "https://somehost.com";

  public String sendPost(String method,
      Map<String, String> methodProperties) throws ClientProtocolException, IOException {

    HttpPost post = new HttpPost(HOST);

    List<NameValuePair> urlParameters = new ArrayList<>();
    urlParameters.add(new BasicNameValuePair("method", method));

    List<NameValuePair> methodPropertiesList = methodProperties.entrySet().stream()
                .map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());

    // ??? urlParameters.add(new BasicNameValuePair("methodProperties", methodPropertiesList));

    post.setEntity(new UrlEncodedFormEntity(urlParameters));

    try (CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(post)) {

      return EntityUtils.toString(response.getEntity());
    }
  }

但是BasicNameValuePair的构造函数适用(String, String)。所以我需要另一堂课。

有没有办法将methodPropertiesList添加到urlParameters

java post apache-httpclient-4.x apache-httpcomponents
2个回答
0
投票
class pojo1{ String method; Map<String,String> methodProperties; } 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);

ref:HTTP POST using JSON in Java


0
投票
static final String HOST = "https://somehost.com"; public String sendPost(String method, Map<String, String> methodProperties) throws ClientProtocolException, IOException { HttpPost post = new HttpPost(HOST); MyResource resource = new MyResource(); resource.setMethod(method); MyNestedResource nestedResource = new MyNestedResource(); nestedResource.setMethodProperties(methodProperties); resource.setNestedResourceMethodProperties(nestedResource); post.setEntity(resource); try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(post)) { return EntityUtils.toString(response.getEntity()); } }

并且通常这就是您使用嵌套结构处理更复杂的json对象的方式。您必须为要发送的资源创建类(在您的示例中,它可能是一个类,并且在其中使用了map,但是如果嵌套对象具有特定的结构,通常也为嵌套对象创建一个类)。为了更好地了解整个图片,请涵盖本教程:https://www.baeldung.com/jackson-mapping-dynamic-object

© www.soinside.com 2019 - 2024. All rights reserved.