http请求post,参数为form-data类型

这种方法主要调用接口参数定义为@RequestParam 的post请求调用。

1.在pom文件是添加引用

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.9</version>
</dependency>
<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>
<dependency>
    <groupId>com.github.pjfanning</groupId>
    <artifactId>xmlbeans</artifactId>
    <version>2.6.5</version>
</dependency>


<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.6.0</version>
</dependency>

<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.9</version>
</dependency>

2. 编写请求代码

public class HttpTextUtils {
   public static Logger logger= LoggerFactory.getLogger(HttpTextUtils.class) ;
    /**
     * POST 请求
     *
     * @param url 目标地址

     * @param params 请求体
     * @return
     */
    public static String doPost(String url, JSONObject params) {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody("params", params.toString(),        ContentType.create("multipart/form-data","utf-8"));
        HttpEntity multipart = builder.build();
        HttpResponse resp = null;
        try {
            httpPost.setEntity(multipart);
            resp = client.execute(httpPost);
           String respnseContent = analysisResopnseContent(resp, HttpStatus.SC_OK);
            logger.info(url+":输入参数"+params.toJSONString(),"输出参数"+respnseContent);
           return respnseContent;
            //注意,返回的结果的状态码是302,非200
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
      return null;
    }

    private static String analysisResopnseContent(HttpResponse response, int expectResponseStatus) throws IOException{
        String resopnseContent = null;
        if (response.getStatusLine().getStatusCode() == expectResponseStatus) {
            HttpEntity responseEntity = response.getEntity();
            resopnseContent = EntityUtils.toString(responseEntity, "utf-8");
        }else{
           return null;
        }
        return resopnseContent;
    }


}

3.调用

String  url = "http://localhost:8080/rest/getUser";
JSONObject obj=new JSONObject();
obj.put("deptName","人事部");
obj.put("handleTime",DateFormatUtil.format_yyyy_MM_dd_HH_mm_ss(new Date()));
obj.put("name","ll");
String result=HttpTextUtils.doPost(url,obj);
经验分享 程序员 微信小程序 职场和发展