• Java使用HttpClient实现远程服务调用


    一、前言
    在项目中,有时需要去调用其他服务的接口,那么我们可以通过httpClient来实现调用。

    二、具体实现
    1.首先定义一个httpClient的工具类

    import org.apache.http.HttpStatus;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.utils.URIBuilder;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicHeader;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    import java.io.IOException;
    import java.net.URI;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    
    public class HttpClientUtil {
    	private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
    	public static String doGet(String url, Map<String, String> param,Map<String, String> header) {
            logger.info("doGetJson,param:{},header:{}",param,header);
    
            // 创建Httpclient对象
            CloseableHttpClient httpclient = HttpClients.createDefault();
    
            String resultString = "";
            CloseableHttpResponse response = null;
            try {
                // 创建uri
                URIBuilder builder = new URIBuilder(url);
                if (param != null) {
                    for (String key : param.keySet()) {
                        builder.addParameter(key, param.get(key));
                    }
                }
                URI uri = builder.build();
    
                // 创建http GET请求
                HttpGet httpGet = new HttpGet(uri);
                //设置请求头
                if (Objects.nonNull(header)) {
                    header.forEach((key, value) -> {
                        httpGet.addHeader(key, value);
                    });
                }
                // 执行请求
                response = httpclient.execute(httpGet);
                 // 判断返回状态是否为200
                if (response.getStatusLine().getStatusCode() == 200) {
                    resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                }
            } catch (Exception e) {
                logger.info("doGet error", e);
            } finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return resultString;
        }
         public static String doPost(String url, Map<String, String> param, Map<String, String> hearder) {
            // 创建Httpclient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
                // 创建Http Post请求
                HttpPost httpPost = new HttpPost(url);
                // 创建参数列表
                if (param != null) {
                    List<NameValuePair> paramList = new ArrayList<>();
                    for (String key : param.keySet()) {
                        paramList.add(new BasicNameValuePair(key, param.get(key)));
                    }
                    // 模拟表单
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                    httpPost.setEntity(entity);
                }
                //设置请求头
               if (Objects.nonNull(hearder)) {
                    hearder.forEach((key, value) -> {
                        httpPost.addHeader(key, value);
                    });
                }
                // 执行http请求
                response = httpClient.execute(httpPost);
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("doPost error", e);
            } finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                    httpClient.close();
                } catch (IOException e) {
                    logger.info("doPost error", e);
                }
            }
    
            return resultString;
        }
        public static String doPostJson(String url, String json,Map<String, String> hearder) throws Exception {
            logger.info("doPostJson,json:{},header:{}",json,hearder);
            // 创建Httpclient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = null;
            try {
                // 对请求的配置,会覆盖全局配置
                RequestConfig requestConfig = RequestConfig.custom()
                        // 设置连接超时时间,单位毫秒,指完成三次tcp握手时间上限
                        .setConnectTimeout(60000)
                        // 读取超时,指从请求的网址获得响应数据的时间间隔
                        .setSocketTimeout(60000)
                        // 指从连接池里面获取响应数据的时间间隔
                        .setConnectionRequestTimeout(60000)
                        .build();
                // 创建Http Post请求
                HttpPost httpPost = new HttpPost(url);
                httpPost.setConfig(requestConfig);
                //设置请求头
                if (Objects.nonNull(hearder)) {
                    hearder.forEach((key, value) -> {
                        httpPost.addHeader(key, value);
                    });
                }
                //json
                StringEntity entity = new StringEntity(json);
                // 给Entity设置Content-Type
                entity.setContentType(new BasicHeader("Content-Type", "application/json; charset=utf-8"));
                httpPost.setEntity(entity);
                // 执行http请求
                response = httpClient.execute(httpPost);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                }
             } catch (Exception e) {
                logger.info("doPostJson error", e);
            } finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException e) {
                    logger.info("doPostJson error", e);
                }
            }
    
            return resultString;
        }
    }
     
    
    • 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
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164

    2.接着我们可以通过这个工具类实现调用,定义一个服务类。

    public class TestService{
    	public DataReturnModeTestlDto signApiConnect(AddParam param) {
            //获取请求头
            Map<String, String> header = param.getHeaders();
            //获取请求体
            Map<String, Object> body = param.getBody();
    		String url = param.getUrl();
    		Map<String, Object> requestParamMap = param.getRequestParam();
    		String requestMethod= param.getRequestMethod();
            try { 
                //判断是get还是post请求
                Map<String, Object> requstInfo = new HashMap<>();
                dto.setRequstInfo(requstInfo);
                requstInfo.put(HTTP_METH, requestMethod);
                String responseBody = null;
                if (BizConstants.HTTP_GET.equals(requestMethod)) {
                    //get请求
                    responseBody = HttpClientUtil.doGet(url, requstParam, header);
                } else if (BizConstants.HTTP_POST.equals(requestMethod)) {
                    //post请求
                    responseBody = HttpClientUtil.doPostJson(url, JSON.toJSONString(body), header);
                    requstInfo.put(IP, url);
                    requstInfo.put(REQUEST_PARAM, body);
                }
                dto.setData(responseBody);
            } catch (Exception exception) {
                throw new BizException("请求失败");
            }
            return dto;
        }
         
    }
    
    • 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

    最后我们可以尝试调用下接口。

  • 相关阅读:
    [CM311-1A]-全网最全 Android 用户管理及用户应用权限
    vue2.7 火影版本,难道只是vue3的过度版?
    旋转的指示牌
    Java虚拟机栈
    RabbitMQ(控制台模拟收发消息与数据隔离)
    商城项目10_JSR303常用注解、在项目中如何使用、统一处理异常、分组校验功能、自定义校验注解
    React报错之map() is not a function
    java计算机毕业设计ssm+jsp线上授课系统
    五、Nginx 配置 https
    bp神经网络遗传算法举例,bp神经网络 遗传算法
  • 原文地址:https://blog.csdn.net/qq_42077317/article/details/132907407