远程调用工具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(); //获取结果
相关文章
|
Java 微服务
【SpringBoot】SpringBoot工程 自定义配置文件
【SpringBoot】SpringBoot工程 自定义配置文件
469 0
|
Java 调度 Spring
Spring之定时任务基本使用篇
本文介绍了在Spring Boot项目中使用定时任务的基本方法。主要通过`@Scheduled`注解实现,需添加`@EnableScheduling`开启定时任务功能。文中详细解析了Cron表达式的语法及常见实例,如每秒、每天特定时间执行等。此外,还探讨了多个定时任务的执行方式(并行或串行)及其潜在问题,并留待后续深入讨论。
888 64
封装httpclient工具类
httpclient远程调用工具封装使用
|
SQL JavaScript Java
Spring Boot 3 整合 Mybatis-Plus 实现数据权限控制
本文介绍了如何在Spring Boot 3中整合MyBatis-Plus实现数据权限控制,通过使用MyBatis-Plus提供的`DataPermissionInterceptor`插件,在不破坏原有代码结构的基础上实现了细粒度的数据访问控制。文中详细描述了自定义注解`DataScope`的使用方法、`DataPermissionHandler`的具体实现逻辑,以及根据用户的不同角色和部门动态添加SQL片段来限制查询结果。此外,还展示了基于Spring Boot 3和Vue 3构建的前后端分离快速开发框架的实际应用案例,包括项目的核心功能模块如用户管理、角色管理等,并提供Gitee上的开源仓库
3473 11
|
Java Apache Spring
Java发送Http请求(HttpClient)
Java发送Http请求(HttpClient)
13559 2
|
编解码 JSON 网络安全
技术经验分享:Javahttpclent请求httpclentUtils工具类
技术经验分享:Javahttpclent请求httpclentUtils工具类
|
Java 数据库连接 数据库
mybatis-plus报错:Can not find table primary key in Class
mybatis-plus报错:Can not find table primary key in Class
2629 1
|
小程序 Java Maven
springboot开发微信小程序
springboot开发微信小程序
772 0
|
Java 程序员
Java多线程基础-16:简述Java并发编程JUC中的Callable接口
Callable接口是Java中用于描述带有返回值任务的接口,与Runnable相对,后者无返回值。Callable的call()方法用于执行具体任务并返回结果。
677 0
|
SQL 前端开发
基于jeecgboot的flowable驳回修改以及发起人设置
基于jeecgboot的flowable驳回修改以及发起人设置
731 0