当前位置:网站首页>Implement sending post request with form data parameter

Implement sending post request with form data parameter

2022-07-06 10:14:00 Eric-x

When docking with a third-party interface , Find out Request parameters Body To use multipart/form-data Mode submission . Then I went to collect some information , It is hereby recorded that

/** *  With post Call the third-party interface , With form-data  form   send data  * * @param url post request url * @param paramMap  Other parameters in the form  * @return */
public static String doPost(String url, Map<String, String> paramMap) {
    
  //  establish Http example 
  CloseableHttpClient httpClient = HttpClients.createDefault();
  //  establish HttpPost example 
  HttpPost httpPost = new HttpPost(url);       
  try {
    
      MultipartEntityBuilder builder = MultipartEntityBuilder.create();
      builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
      builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
      
      // Parameters in the form 
     for(Map.Entry<String, String> entry: paramMap.entrySet()) {
    
          builder.addPart(entry.getKey(),new StringBody(entry.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
      }
     
      HttpEntity entity = builder.build();
      httpPost.setEntity(entity);
      HttpResponse response = httpClient.execute(httpPost);//  Execute commit 
                
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    
          //  return 
          String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));
          return res;
      }
     
  } catch (Exception e) {
    
      e.printStackTrace();
      logger.error(" call HttpPost Failure !" + e.toString());
  } finally {
    
      if (httpClient != null) {
    
          try {
    
              httpClient.close();
          } catch (IOException e) {
    
              logger.error(" close HttpPost The connection fails !");
          }
      }
  }       
  return null;              
}


Then let's put the dependency I use

<!-- httpclient  Related dependencies -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5</version>
</dependency>

And if you use PostMan If tested in this way , That's true .
 Insert picture description here

Reference resources :https://blog.csdn.net/LYY1448019681/article/details/115124407

原网站

版权声明
本文为[Eric-x]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060910053368.html