wzy
2021-01-18 b8b9ba738ce614820a46c6700e5400984c4e5b58
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.matrix.component.tools;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.matrix.core.exception.GlobleException;
import com.matrix.core.tools.LogUtil;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
 
import java.io.IOException;
 
/**
 * POST 请求工具
 */
public class HttpClientUtil {
 
    public static JSONObject sendPostWithJson(String url, String json) {
 
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            //第一步:创建HttpClient对象
            httpClient = HttpClients.createDefault();
 
            //第二步:创建httpPost对象
            HttpPost httpPost = new HttpPost(url);
 
            //第三步:给httpPost设置JSON格式的参数
            StringEntity requestEntity = new StringEntity(json, "utf-8");
            requestEntity.setContentEncoding("UTF-8");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(requestEntity);
            //第四步:发送HttpPost请求,获取返回值
            String returnValue = httpClient.execute(httpPost, responseHandler); //调接口获取返回值时,必须用此方法
            return JSON.parseObject(returnValue);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                LogUtil.error("http请求发送失败", e);
                throw new GlobleException(e.getMessage());
            }
        }
        //第五步:处理返回值
        return null;
    }
 
 
}