【问题标题】:How to pass complex parameter to POST request using Apache HTTP client?如何使用 Apache HTTP 客户端将复杂参数传递给 POST 请求?
【发布时间】:2019-10-31 11:17:47
【问题描述】:

我尝试使用这样的正文发送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


    【解决方案1】:

    您的请求看起来像一个 json 结构,因此请发布如下数据:

     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);
    

    参考:HTTP POST using JSON in Java

    【讨论】:

      【解决方案2】:

      有一个众所周知的方法来解决这个问题。 在大多数情况下,您将创建自己的对象来描述要在 HttpPost 中发送的内容。所以你会有类似的东西:

      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);
      
          StringEntity strEntity = new StringEntity(gson.toJson(resource));
          post.setEntity(strEntity);
      
          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

      【讨论】:

      • 我理解你的想法,但是setEntity 有这样的签名(org.apache.http.HttpEntity entity)。要实现HttpEntity,我必须实现一堆方法
      • 是的,很抱歉你可以使用这个:StringEntity strEntity= new StringEntity(gson.toJson(resource));我也会编辑我的答案。
      【解决方案3】:

      使用 Sushil Mittal 回答这里是我的解决方案

      static final String HOST = "https://somehost.com";
      
        public String sendPost(String method, Map<String, String> methodProperties) throws ClientProtocolException, IOException {
      
          HttpPost post = new HttpPost(HOST);  
          Gson gson = new Gson();
      
          Params params = new Params(method, methodProperties);
          StringEntity entity = new StringEntity(gson.toJson(params));   
          post.setEntity(entity);
      
          try (CloseableHttpClient httpClient = HttpClients.createDefault();
              CloseableHttpResponse response = httpClient.execute(post)) {
      
            return EntityUtils.toString(response.getEntity());
          }
        }
      

        class Params {
      
          String method;   
          Map<String, String> methodProperties;
      
          public Params(String method, Map<String, String> methodProperties) {
            this.method = method;
            this.methodProperties = methodProperties;
          }
      
          //getters
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-31
        • 1970-01-01
        • 1970-01-01
        • 2014-12-21
        • 1970-01-01
        • 2016-06-16
        • 2012-10-22
        • 1970-01-01
        相关资源
        最近更新 更多