与第三方对接进行httpClient调用的几种方式解析【一篇教你学会对接三方接口】

项目场景:

与第三方对接:

涉及到与第三方对接httpClient调用的几种方式(httpGet、HttpPost、HttpDelete、HttpPut):
其中还有一种是获取头部信息的,然后进行取值(取个名叫 httpPostHead)


代码解析:

httpGet方法调用:

    public static String doGet(String url, Map<String, String> headers, Map<String, Object> param) {
        // 创建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, String.valueOf(param.get(key)));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 处理头部参数
            if (null != headers){
                for (String key : headers.keySet()) {
                    httpGet.setHeader(key, headers.get(key));
                }
            }
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

httpPost方法调用:

	private static PoolingHttpClientConnectionManager connectionManager;

    static {
        //定义一个连接池的工具类对象
        connectionManager = new PoolingHttpClientConnectionManager();
        //定义连接池属性
        //定义连接池最大的连接数
        connectionManager.setMaxTotal(300);
        //定义主机的最大的并发数
        connectionManager.setDefaultMaxPerRoute(50);
    }

	
    public static String doPost(String url, Map<String, String> headers, Map<String, Object> param) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");

        if (null != headers){
            for (String key : headers.keySet()) {
                httpPost.setHeader(key, headers.get(key));
            }
        }

        String s = JSON.toJSONString(param);
        StringEntity stringEntity = new StringEntity(s, StandardCharsets.UTF_8);
        httpPost.setEntity(stringEntity);

        return execute(httpPost);
    }

    private static String execute(HttpRequestBase httpRequestBase) throws IOException {

        httpRequestBase.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36");

        /**
         * setConnectionRequestTimeout:设置获取请求的最长时间
         *
         * setConnectTimeout: 设置创建连接的最长时间
         *
         * setSocketTimeout: 设置传输超时的最长时间
         */

        RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000)
                .setSocketTimeout(10 * 1000).build();

        httpRequestBase.setConfig(config);
        
        CloseableHttpClient httpClient = getCloseableHttpClient();

        CloseableHttpResponse response = httpClient.execute(httpRequestBase);
        String html;
        if(response.getStatusLine().getStatusCode()==200){
            html = EntityUtils.toString(response.getEntity(), "GBK");
        }else{
            html = null;
        }
        return html;
    }
    
    private static CloseableHttpClient getCloseableHttpClient() {

        RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(5000)
            .setSocketTimeout(10000)
            .setConnectTimeout(5000)
            .build();

        return HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).build();
    }

connectionManager 这个为连接池的工具类对象

httpDelete方法调用:

    public static String doDelete(String url, Map<String, String> headers, Map<String, Object> param) throws Exception {
        CloseableHttpClient httpClient = getCloseableHttpClient();

        // 创建自定义的DELETE请求
        CustomHttpDelete httpDelete = new CustomHttpDelete(url);

        httpDelete.setHeader("Content-Type", "application/json;charset=UTF-8");

        if (null != headers) {
            for (String key : headers.keySet()) {
                httpDelete.setHeader(key, headers.get(key));
            }
        }
        String jsonString = JSON.toJSONString(param);

        StringEntity stringEntity = new StringEntity(jsonString, StandardCharsets.UTF_8);

        httpDelete.setEntity(stringEntity);

        // 执行请求
        CloseableHttpResponse response = httpClient.execute(httpDelete);

        String html;
        if (response.getStatusLine().getStatusCode() == 202 || response.getStatusLine().getStatusCode() == 200) {
            html = EntityUtils.toString(response.getEntity(), "GBK");
        } else if (response.getStatusLine().getStatusCode() == 500){
            html = "500";
        } else {
            html = null;
        }
        return html;
    }
// 自定义CustomHttpDelete 
public class CustomHttpDelete extends HttpEntityEnclosingRequestBase {

    public static final String METHOD_NAME = "DELETE";

    @Override
    public String getMethod() {
        return METHOD_NAME;
    }

    public CustomHttpDelete(final String uri) {
        super();
        setURI(URI.create(uri));
    }

    public CustomHttpDelete(final URI uri) {
        super();
        setURI(uri);
    }

    public CustomHttpDelete() {
        super();
    }

}
    

httpPut方法调用:

public static String doPut(String url, Map<String, String> headers, Map<String, Object> param) throws Exception {
        CloseableHttpClient httpClient = getCloseableHttpClient();

        HttpPut httpPut = new HttpPut(url);

        httpPut.setHeader("Content-Type", "application/json;charset=UTF-8");

        if (null != headers) {
            for (String key : headers.keySet()) {
                httpPut.setHeader(key, headers.get(key));
            }
        }
        String s = JSON.toJSONString(param);

        StringEntity stringEntity = new StringEntity(s, StandardCharsets.UTF_8);

        httpPut.setEntity(stringEntity);

        CloseableHttpResponse response = httpClient.execute(httpPut);

        String html;
        if (response.getStatusLine().getStatusCode() == 202 || response.getStatusLine().getStatusCode() == 200) {
            html = EntityUtils.toString(response.getEntity(), "GBK");
        } else if (response.getStatusLine().getStatusCode() == 500){
            html = "500";
        } else {
            html = null;
        }
        return html;
    }

httpPostHead方法调用:

public static CloseableHttpResponse doPostHead(String url, Map<String, Object> param) throws IOException {

        CloseableHttpClient httpClient = getCloseableHttpClient();

        HttpPost httpPost = new HttpPost(url);

        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");

        String s = JSON.toJSONString(param);

        StringEntity stringEntity = new StringEntity(s, StandardCharsets.UTF_8);

        httpPost.setEntity(stringEntity);

        return httpClient.execute(httpPost);

    }

在这里会返回CloseableHttpResponse类型的数据。只需要从CloseableHttpResponse中获取头部参数数据即可。示例:

	CloseableHttpResponse response = HttpClientUtils.doPostHead(requestUrl, param);
	Header[] allHeaders = response.getAllHeaders();
	String result = "";
	for (Header header : allHeaders) {
	    if ("token".equals(header.getName())) {
	        result = header.getValue();
	    }
	}   

在这里HttpClientUtils是封装的工具类,把这些方法粘进去自己去封装一下能调用即可,就不过多介绍。 其中result 就是我们获取头部参数为token的值。


问题描述:

分析一:看完你会发现response.getStatusLine().getStatusCode()会出现202的情况,其实这个具体示当时场景而定,看返回来的值是什么。还有自定义response.getStatusLine().getStatusCode()为500时候的返回值,也是当时情境需要。

分析二: 如果发现httpDelete、httpPut、httpPostHead有报红的参数,去httpPost方法里面找一下,里面代码比较全面。

分析三:httpDelete请求是自己定义的CustomHttpDelete。为什么要自定义呢,因为httpDelete请求需要传参,不能直接添加到url里面调用。

遗留问题:当频繁调用httpPost或HttpDelete或httpPut等方法的时候,会出现超时的情况。 有大佬看到并且有好的方法,可以留言,欢迎一起讨论。 (我大胆猜测一下,可能是因为没有释放资源所致。)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值