HttpClient
发布日期:2021-06-28 20:54:12 浏览次数:2 分类:技术文章

本文共 23932 字,大约阅读时间需要 79 分钟。

目录


 

在日常项目开发中,有时候我们需要调用第三方接口数据,常用的方法有传统JDK自带的URLConnection,Apache Jakarta Common下的子项目HttpClient ,Spring的RestTemplate。

在SpringBoot项目下,使用不同的方式调用心知天气接口,

一、HttpClient

HttpClient的主要功能:

  • 实现了所有 HTTP 的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)
  • 支持 HTTPS 协议
  • 支持代理服务器(Nginx等)等
  • 支持自动(跳转)转向

环境说明:JDK1.8、SpringBoot

准备环节

第一步:在pom.xml中引入HttpClient的依赖

org.apache.httpcomponents
httpclient
4.5.3

第二步:引入fastjson依赖

com.alibaba
fastjson
1.2.15

注:本人引入此依赖的目的是,在后续示例中,会用到“将对象转化为json字符串的功能”,也可以引其他有此功能的依赖。 

注:SpringBoot的基本依赖配置,这里就不再多说了。

 

详细使用示例

【步骤】:

1)创建一个httpclient对象,注意以下版本问题说明
HttpClient4.0版本前:
HttpClient httpClient = new DefaultHttpClient();
4.0版本后:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
2)创建一个httpGet对象
HttpGet request = new HttpGet(uri);
3)执行请求调用httpclient的execute(),传入httpGet对象,返回CloseableHttpResponse response = httpClient.execute(request, HttpClientContext.create());
4)取得响应结果并处理
5)关闭HttpClient

response.close();httpClient.close();
// 1.创建一个httpclient对象        CloseableHttpClient httpClient = HttpClientBuilder.create().build();        // 2.创建一个httpGet对象        HttpGet request = new HttpGet(uri);        CloseableHttpResponse response = null;        try {            // 3.执行请求调用httpclient的execute(),传入httpGet对象,返回CloseableHttpResponse            response = httpClient.execute(request, HttpClientContext.create());            // 4.取得响应结果并处理            HttpEntity entity = response.getEntity();            String responseString = EntityUtils.toString(entity);
主动设置编码,防止响应出现乱码

 

GET无参

先新建一个Spring Boot 项目用于JAVA发送HttpClient(在test里面单元测试发送的)

package com.example.demo;import org.apache.http.HttpEntity;import org.apache.http.ParseException;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.util.EntityUtils;import org.junit.jupiter.api.Test;import org.springframework.boot.test.context.SpringBootTest;import java.io.IOException;@SpringBootTestclass DemoApplicationTests {    @Test    public void doGetTestOne() {        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)        CloseableHttpClient httpClient = HttpClientBuilder.create().build();        // 创建Get请求        HttpGet httpGet = new HttpGet("http://localhost:8080/out");        // 响应模型        CloseableHttpResponse response = null;        try {            // 由客户端执行(发送)Get请求            response = httpClient.execute(httpGet);            // 从响应模型中获取响应实体            HttpEntity responseEntity = response.getEntity();            System.out.println("响应状态为:" + response.getStatusLine());            if (responseEntity != null) {                System.out.println("响应内容长度为:" + responseEntity.getContentLength());                //主动设置编码,防止相应出现乱码                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));            }        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (ParseException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                // 释放资源                if (httpClient != null) {                    httpClient.close();                }                if (response != null) {                    response.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }    }}

用于JAVA接收的(在controller里面接收的)

package com.imooc.myspringboot.controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class HttpClient {  /**     * GET 无参     * @return     */    @RequestMapping("/getNoParam")    public String getNoParam(){        return "GetControllerOut";    }}

先启动,用于JAVA接收的(在controller里面接收的)的项目,再自启动用于JAVA发送HttpClient(在test里面单元测试发送的)

控制打印结果:

以下均为先在用controller里面接收的,在test里面单元测试发送

GET有参(方式一:直接拼接URL)

/**GET有参(方式一:直接拼接URL):     * GET---有参测试 (方式一:手动在url后面加上参数)     *     * @date 2018年7月13日 下午4:19:23     */    @Test    public void doGetTestWayOne() {        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)        CloseableHttpClient httpClient = HttpClientBuilder.create().build();        // 参数        StringBuffer params = new StringBuffer();        try {            // 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)            params.append("name=" + URLEncoder.encode("张三", "utf-8"));            params.append("&");            params.append("age=24");        } catch (UnsupportedEncodingException e1) {            e1.printStackTrace();        }        // 创建Get请求        HttpGet httpGet = new HttpGet("http://localhost:8080/getHaveParam" + "?" + params);        // 响应模型        CloseableHttpResponse response = null;        try {            // 配置信息            RequestConfig requestConfig = RequestConfig.custom()                    // 设置连接超时时间(单位毫秒)                    .setConnectTimeout(5000)                    // 设置请求超时时间(单位毫秒)                    .setConnectionRequestTimeout(5000)                    // socket读写超时时间(单位毫秒)                    .setSocketTimeout(5000)                    // 设置是否允许重定向(默认为true)                    .setRedirectsEnabled(true).build();            // 将上面的配置信息 运用到这个Get请求里            httpGet.setConfig(requestConfig);            // 由客户端执行(发送)Get请求            response = httpClient.execute(httpGet);            // 从响应模型中获取响应实体            HttpEntity responseEntity = response.getEntity();            System.out.println("响应状态为:" + response.getStatusLine());            if (responseEntity != null) {                System.out.println("响应内容长度为:" + responseEntity.getContentLength());                //主动设置编码,防止相应出现乱码                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));            }        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (ParseException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                // 释放资源                if (httpClient != null) {                    httpClient.close();                }                if (response != null) {                    response.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }    }

 

/**     * GET有参     */    @RequestMapping("/getHaveParam")    public String getHaveParam(String name,Integer age){        return "====="+name+"  "+age+"=====";    }

GET有参(方式二:使用URI获得HttpGet)

/**     * GET有参(方式二:使用URI获得HttpGet):     * GET---有参测试 (方式二:将参数放入键值对类中,再放入URI中,从而通过URI得到HttpGet实例)     *     *     */    @Test    public void doGetTestWayTwo() {        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)        CloseableHttpClient httpClient = HttpClientBuilder.create().build();        // 参数        URI uri = null;        try {            // 将参数放入键值对类NameValuePair中,再放入集合中            List
params = new ArrayList<>(); params.add(new BasicNameValuePair("name", "王五")); params.add(new BasicNameValuePair("age", "30")); // 设置uri信息,并将参数集合放入uri; // 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value) uri = new URIBuilder().setScheme("http").setHost("localhost") .setPort(8080).setPath("/getHaveParam") .setParameters(params).build(); } catch (URISyntaxException e1) { e1.printStackTrace(); } // 创建Get请求 HttpGet httpGet = new HttpGet(uri); // 响应模型 CloseableHttpResponse response = null; try { // 配置信息 RequestConfig requestConfig = RequestConfig.custom() // 设置连接超时时间(单位毫秒) .setConnectTimeout(5000) // 设置请求超时时间(单位毫秒) .setConnectionRequestTimeout(5000) // socket读写超时时间(单位毫秒) .setSocketTimeout(5000) // 设置是否允许重定向(默认为true) .setRedirectsEnabled(true).build(); // 将上面的配置信息 运用到这个Get请求里 httpGet.setConfig(requestConfig); // 由客户端执行(发送)Get请求 response = httpClient.execute(httpGet); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); System.out.println("响应状态为:" + response.getStatusLine()); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); //主动设置编码,防止相应出现乱码 System.out.println("响应内容为:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }
/**     * GET有参     */    @RequestMapping("/getHaveParam")    public String getHaveParam(String name,Integer age){        return "====="+name+"  "+age+"=====";    }

POST无参

/**     * POST---无参测试     *     *     */    @Test    public void doPostNoParamTest() {        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)        CloseableHttpClient httpClient = HttpClientBuilder.create().build();        // 创建Post请求        HttpPost httpPost = new HttpPost("http://localhost:8080/postNoParam");        // 响应模型        CloseableHttpResponse response = null;        try {            // 由客户端执行(发送)Post请求            response = httpClient.execute(httpPost);            // 从响应模型中获取响应实体            HttpEntity responseEntity = response.getEntity();            System.out.println("响应状态为:" + response.getStatusLine());            if (responseEntity != null) {                System.out.println("响应内容长度为:" + responseEntity.getContentLength());                //主动设置编码,防止相应出现乱码                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));            }        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (ParseException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                // 释放资源                if (httpClient != null) {                    httpClient.close();                }                if (response != null) {                    response.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }    }
/**     * Post没有参数     * @return     */    @RequestMapping(value = "/postNoParam",method = RequestMethod.POST)    public String postNoParam(){        return "这个是没有参数的post请求";    }

 

POST有参(普通参数)

/**POST有参(普通参数):     * POST---有参测试(普通参数)     *     *     */    @Test    public void doPostTestFour() {        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)        CloseableHttpClient httpClient = HttpClientBuilder.create().build();        // 参数        StringBuffer params = new StringBuffer();        try {            // 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)            params.append("name=" + URLEncoder.encode("&", "utf-8"));            params.append("&");            params.append("age=24");        } catch (UnsupportedEncodingException e1) {            e1.printStackTrace();        }        // 创建Post请求        HttpPost httpPost = new HttpPost("http://localhost:8080/postNoParam" + "?" + params);        // 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)        httpPost.setHeader("Content-Type", "application/json;charset=utf8");        // 响应模型        CloseableHttpResponse response = null;        try {            // 由客户端执行(发送)Post请求            response = httpClient.execute(httpPost);            // 从响应模型中获取响应实体            HttpEntity responseEntity = response.getEntity();            System.out.println("响应状态为:" + response.getStatusLine());            if (responseEntity != null) {                System.out.println("响应内容长度为:" + responseEntity.getContentLength());               //主动设置编码,防止相应出现乱码                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));            }        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (ParseException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                // 释放资源                if (httpClient != null) {                    httpClient.close();                }                if (response != null) {                    response.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }    }
@RequestMapping(value = "/postNoParam",method = RequestMethod.POST)     public String postNoParam(){        return "这个是没有参数的post请求";     }

POST有参(对象参数)

首先创建一个User类

package com.example.demo.domain;public class User {    private String userName;    private String password;    public User() {    }    public User(String userName, String password) {        this.userName = userName;        this.password = password;    }    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    @Override    public String toString() {        return "User{" +                "userName='" + userName + '\'' +                ", password='" + password + '\'' +                '}';    }}
/**     * POST---有参测试(对象参数)     *     * @date     */    @Test    public void dopostHaveObjectParam() {        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)        CloseableHttpClient httpClient = HttpClientBuilder.create().build();        // 创建Post请求        HttpPost httpPost = new HttpPost("http://localhost:8080/postHaveObjectParam");        User user = new User();        user.setUserName("王网");        user.setPassword("Ss@1234");        // 我这里利用阿里的fastjson,将Object转换为json字符串;        // (需要导入com.alibaba.fastjson.JSON包)        String jsonString = JSON.toJSONString(user);        StringEntity entity = new StringEntity(jsonString, "UTF-8");        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中        httpPost.setEntity(entity);        httpPost.setHeader("Content-Type", "application/json;charset=utf8");        // 响应模型        CloseableHttpResponse response = null;        try {            // 由客户端执行(发送)Post请求            response = httpClient.execute(httpPost);            // 从响应模型中获取响应实体            HttpEntity responseEntity = response.getEntity();            System.out.println("响应状态为:" + response.getStatusLine());            if (responseEntity != null) {                System.out.println("响应内容长度为:" + responseEntity.getContentLength());               //主动设置编码,防止相应出现乱码                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));            }        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (ParseException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                // 释放资源                if (httpClient != null) {                    httpClient.close();                }                if (response != null) {                    response.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }    }
/**     * Post有参(对象参数)     * @return     */    @RequestMapping(value = "/postHaveObjectParam",method = RequestMethod.POST)    public String postHaveObjectParam(@RequestBody User user) {        return "这个是有对象参数的post请求"+user.toString();    }

POST有参(普通参数 + 对象参数)

注:POST传递普通参数时,方式与GET一样即可,这里以通过URI获得HttpPost的方式为例。

/**     * POST---有参测试(普通参数 + 对象参数)     *     *     */    @Test    public void dopostHaveObjectAndCommonParamTest() {        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)        CloseableHttpClient httpClient = HttpClientBuilder.create().build();        // 创建Post请求        // 参数        URI uri = null;        try {            // 将参数放入键值对类NameValuePair中,再放入集合中            List
params = new ArrayList<>(); params.add(new BasicNameValuePair("flag", "6")); params.add(new BasicNameValuePair("meaning", "小星星")); // 设置uri信息,并将参数集合放入uri; // 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value) uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(8080) .setPath("/postHaveObjectAndCommonParam").setParameters(params).build(); } catch (URISyntaxException e1) { e1.printStackTrace(); } HttpPost httpPost = new HttpPost(uri); // HttpPost httpPost = new // HttpPost("http://localhost:8080/postHaveObjectAndCommonParam"); // 创建user参数 User user = new User(); user.setUserName("王网"); user.setPassword("Ss@1234"); // 将user对象转换为json字符串,并放入entity中 StringEntity entity = new StringEntity(JSON.toJSONString(user), "UTF-8"); // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中 httpPost.setEntity(entity); httpPost.setHeader("Content-Type", "application/json;charset=utf8"); // 响应模型 CloseableHttpResponse response = null; try { // 由客户端执行(发送)Post请求 response = httpClient.execute(httpPost); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); System.out.println("响应状态为:" + response.getStatusLine()); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); //主动设置编码,防止相应出现乱码 System.out.println("响应内容为:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }
/**     * Post有参(对象参数+普通参数)     * @return     */    @RequestMapping(value = "/postHaveObjectAndCommonParam",method = RequestMethod.POST)    public String postHaveObjectAndCommonParam(@RequestBody User user,Integer flag,String meaning) {        return "这个是有对象参数+普通参数的post请求"+user.toString()+"flag:"+flag+"  "+"meaning:"+meaning;    }

 

进行HTTPS请求并进行(或不进行)证书校验(示例)

进行HTTPS请求并进行(或不进行)证书校验(示例)中相关方法详情(非完美封装):

/** * 根据是否是https请求,获取HttpClient客户端 * * TODO 本人这里没有进行完美封装。对于 校不校验校验证书的选择,本人这里是写死 *      在代码里面的,你们再使用时,可以灵活二次封装。 * * 提示: 此工具类的封装、相关客户端、服务端证书的生成,可参考我的这篇博客: *      
https://blog.csdn.net/justry_deng/article/details/91569132
* * * @param isHttps 是否是HTTPS请求 * * @return HttpClient实例 * @date 2019/9/18 17:57 */private CloseableHttpClient getHttpClient(boolean isHttps) { CloseableHttpClient httpClient; if (isHttps) { SSLConnectionSocketFactory sslSocketFactory; try { /// 如果不作证书校验的话 sslSocketFactory = getSocketFactory(false, null, null); /// 如果需要证书检验的话 // 证书 //InputStream ca = this.getClass().getClassLoader().getResourceAsStream("client/ds.crt"); // 证书的别名,即:key。 注:cAalias只需要保证唯一即可,不过推荐使用生成keystore时使用的别名。 // String cAalias = System.currentTimeMillis() + "" + new SecureRandom().nextInt(1000); //sslSocketFactory = getSocketFactory(true, ca, cAalias); } catch (Exception e) { throw new RuntimeException(e); } httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslSocketFactory).build(); return httpClient; } httpClient = HttpClientBuilder.create().build(); return httpClient;} /** * HTTPS辅助方法, 为HTTPS请求 创建SSLSocketFactory实例、TrustManager实例 * * @param needVerifyCa * 是否需要检验CA证书(即:是否需要检验服务器的身份) * @param caInputStream * CA证书。(若不需要检验证书,那么此处传null即可) * @param cAalias * 别名。(若不需要检验证书,那么此处传null即可) * 注意:别名应该是唯一的, 别名不要和其他的别名一样,否者会覆盖之前的相同别名的证书信息。别名即key-value中的key。 * * @return SSLConnectionSocketFactory实例 * @throws NoSuchAlgorithmException * 异常信息 * @throws CertificateException * 异常信息 * @throws KeyStoreException * 异常信息 * @throws IOException * 异常信息 * @throws KeyManagementException * 异常信息 * @date 2019/6/11 19:52 */private static SSLConnectionSocketFactory getSocketFactory(boolean needVerifyCa, InputStream caInputStream, String cAalias) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException { X509TrustManager x509TrustManager; // https请求,需要校验证书 if (needVerifyCa) { KeyStore keyStore = getKeyStore(caInputStream, cAalias); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); } x509TrustManager = (X509TrustManager) trustManagers[0]; // 这里传TLS或SSL其实都可以的 SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{x509TrustManager}, new SecureRandom()); return new SSLConnectionSocketFactory(sslContext); } // https请求,不作证书校验 x509TrustManager = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) { } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) { // 不验证 } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{x509TrustManager}, new SecureRandom()); return new SSLConnectionSocketFactory(sslContext);} /** * 获取(密钥及证书)仓库 * 注:该仓库用于存放 密钥以及证书 * * @param caInputStream * CA证书(此证书应由要访问的服务端提供) * @param cAalias * 别名 * 注意:别名应该是唯一的, 别名不要和其他的别名一样,否者会覆盖之前的相同别名的证书信息。别名即key-value中的key。 * @return 密钥、证书 仓库 * @throws KeyStoreException 异常信息 * @throws CertificateException 异常信息 * @throws IOException 异常信息 * @throws NoSuchAlgorithmException 异常信息 * @date 2019/6/11 18:48 */private static KeyStore getKeyStore(InputStream caInputStream, String cAalias) throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException { // 证书工厂 CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); // 秘钥仓库 KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); keyStore.setCertificateEntry(cAalias, certificateFactory.generateCertificate(caInputStream)); return keyStore;}

 

转载地址:https://blog.csdn.net/yangshengwei230612/article/details/103851413 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:HttpClient -- StringEntity 编码问题
下一篇:用idea搭建一个swagger-demo

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月25日 18时59分02秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章