远程调用工具HttpClient工具类封装

简介: java远程调用工具HttpClient工具类类封装

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。

HttpClient通俗的讲就是模拟了浏览器的行为,如果我们需要在后端向某一地址提交数据获取结果,就可以使用HttpClient.

关于HttpClient(原生)具体的使用不属于我们这里的学习内容,我们这里这里为了简化HttpClient的使用,提供了工具类HttpClient(对原生HttpClient进行了封装)

依赖

<!--httpclient支持-->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
</dependency>

HttpClient工具类代码:

public class HttpClient {
   
    private String url;
    private Map<String, String> param;
    private int statusCode;
    private String content;
    private String xmlParam;
    private boolean isHttps;

    public boolean isHttps() {
   
        return isHttps;
    }

    public void setHttps(boolean isHttps) {
   
        this.isHttps = isHttps;
    }

    public String getXmlParam() {
   
        return xmlParam;
    }

    public void setXmlParam(String xmlParam) {
   
        this.xmlParam = xmlParam;
    }

    public HttpClient(String url, Map<String, String> param) {
   
        this.url = url;
        this.param = param;
    }

    public HttpClient(String url) {
   
        this.url = url;
    }

    public void setParameter(Map<String, String> map) {
   
        param = map;
    }

    public void addParameter(String key, String value) {
   
        if (param == null)
            param = new HashMap<String, String>();
        param.put(key, value);
    }

    public void post() throws ClientProtocolException, IOException {
   
        HttpPost http = new HttpPost(url);
        setEntity(http);
        execute(http);
    }

    public void put() throws ClientProtocolException, IOException {
   
        HttpPut http = new HttpPut(url);
        setEntity(http);
        execute(http);
    }

    public void get() throws ClientProtocolException, IOException {
   
        if (param != null) {
   
            StringBuilder url = new StringBuilder(this.url);
            boolean isFirst = true;
            for (String key : param.keySet()) {
   
                if (isFirst) {
   
                    url.append("?");
                }else {
   
                    url.append("&");
                }
                url.append(key).append("=").append(param.get(key));
            }
            this.url = url.toString();
        }
        HttpGet http = new HttpGet(url);
        execute(http);
    }

    /**
     * set http post,put param
     */
    private void setEntity(HttpEntityEnclosingRequestBase http) {
   
        if (param != null) {
   
            List<NameValuePair> nvps = new LinkedList<NameValuePair>();
            for (String key : param.keySet()) {
   
                nvps.add(new BasicNameValuePair(key, param.get(key))); // 参数
            }
            http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // 设置参数
        }
        if (xmlParam != null) {
   
            http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));
        }
    }

    private void execute(HttpUriRequest http) throws ClientProtocolException,
            IOException {
   
        CloseableHttpClient httpClient = null;
        try {
   
            if (isHttps) {
   
                SSLContext sslContext = new SSLContextBuilder()
                        .loadTrustMaterial(null, new TrustStrategy() {
   
                            // 信任所有
                            @Override
                            public boolean isTrusted(X509Certificate[] chain,
                                                     String authType)
                                    throws CertificateException {
   
                                return true;
                            }
                        }).build();
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                        sslContext);
                httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
                        .build();
            } else {
   
                httpClient = HttpClients.createDefault();
            }
            CloseableHttpResponse response = httpClient.execute(http);
            try {
   
                if (response != null) {
   
                    if (response.getStatusLine() != null) {
   
                        statusCode = response.getStatusLine().getStatusCode();
                    }
                    HttpEntity entity = response.getEntity();
                    // 响应内容
                    content = EntityUtils.toString(entity, Consts.UTF_8);
                }
            } finally {
   
                response.close();
            }
        } catch (Exception e) {
   
            e.printStackTrace();
        } finally {
   
            httpClient.close();
        }
    }

    public int getStatusCode() {
   
        return statusCode;
    }

    public String getContent() throws ParseException, IOException {
   
        return content;
    }
}

HttpClient工具类使用的步骤

HttpClient client=new HttpClient(请求的url地址);
client.setHttps(true);//是否是https协议
client.setXmlParam(xmlParam);//发送的xml数据
client.post();//执行post请求
String result = client.getContent(); //获取结果
相关文章
|
5月前
|
Java Apache 网络架构
Java用于远程调用的客户端都有什么?
【6月更文挑战第4天】Java用于远程调用的客户端都有什么?
30 2
|
6月前
|
Java Apache 网络架构
Java用于远程调用的客户端都有什么
【5月更文挑战第18天】Java用于远程调用的客户端都有什么
43 5
|
3月前
|
Android开发
SharePreference封装成工具类
SharePreference封装成工具类
124 1
|
6月前
封装httpclient工具类
httpclient远程调用工具封装使用
|
JSON 数据格式
HttpClient远程调用基本使用(详解)
HttpClient远程调用基本使用(详解)
306 0
|
Java Android开发
okhttp工具类封装
okhttp工具类封装
203 0
|
SQL JSON PHP
分享一下自己封装的Laravel常用工具类
分享一下自己封装的Laravel常用工具类
198 0
Java HttpClient 如何使用代理IP请求接口
Java HttpClient 如何使用代理IP请求接口