HttpClient

alt

HttpClient简介

HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性,它不仅使客户端发送Http请求变得容易,而且也方便开发人员测试接口(基于Http协议的),提高了开发的效率,也方便提高代码的健壮性。

org.apache.commons.httpclient.HttpClientorg.apache.http.client.HttpClient的区别:

Commons的HttpClient项目现在是生命的尽头,不再被开发,已被Apache HttpComponents项目HttpClient和HttpCore组取代,提供更好的性能和更大的灵活性。

HTTP和浏览器有点像,但却不是浏览器。很多人觉得既然HttpClient是一个HTTP客户端编程工具,很多人把他当做浏览器来理解,但是其实HttpClient不是浏览器,它是一个HTTP通信库,因此它只提供一个通用浏览器应用程序所期望的功能子集,最根本的区别是HttpClient中没有用户界面,浏览器需要一个渲染引擎来显示页面,并解释用户输入,例如鼠标点击显示页面上的某处,有一个布局引擎,计算如何显示HTML页面,包括级联样式表和图像。javascript解释器运行嵌入HTML页面或从HTML页面引用的javascript代码。来自用户界面的事件被传递到javascript解释器进行处理。除此之外,还有用于插件的接口,可以处理Applet,嵌入式媒体对象(如pdf文件,Quicktime电影和Flash动画)或ActiveX控件(可以执行任何操作)。HttpClient只能以编程的方式通过其API用于传输和接受HTTP消息。

HttpClient主要功能

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

关于Http的请求类型(常见)

get、put、post、delete含义与区别

1、GET请求会向数据库发索取数据的请求,从而来获取信息,该请求就像数据库的select操作一样,只是用来查询一下数据,不会修改、增加数据,不会影响资源的内容,即该请求不会产生副作用。无论进行多少次操作,结果都是一样的。

2、与GET不同的是,PUT请求是向服务器端发送数据的,从而改变信息,该请求就像数据库的update操作一样,用来修改数据的内容,但是不会增加数据的种类等,也就是说无论进行多少次PUT操作,其结果并没有不同。

3、POST请求同PUT请求类似,都是向服务器端发送数据的,但是该请求会改变数据的种类等资源,就像数据库的insert操作一样,会创建新的内容。几乎目前所有的提交操作都是用POST请求的。

4、DELETE请求顾名思义,就是用来删除某一个资源的,该请求就像数据库的delete操作。

就像前面所讲的一样,既然PUT和POST操作都是向服务器端发送数据的,那么两者有什么区别呢?

  • POST主要作用在一个集合资源之上的(url)。
  • PUT主要作用在一个具体资源之上的(url/xxx)。

通俗地讲:如URL可以在客户端确定,那么可使用PUT,否则用POST。

数据请求格式

综上所述,我们可理解为以下:

1、POST    /url      创建  
2、DELETE  /url/xxx  删除  
3、PUT     /url/xxx  更新
4、GET     /url/xxx  查看

HttpClient的请求类型

实现了所有的Http请求类型,相应的类为

HttpGet、HttpPost、HttpDelete、HttpPut

在学习HttpClient之前,我们得知道HTTP协议的响应状态码一共有哪些?下图已列出了所有的响应状态码。

alt

平常开发遇到的常见的响应状态码:

alt

Http的使用流程

利用httpClient去访问接口的步骤一般是:

  1. 创建HttpClient对象。
  2. 构造Http请求对象。
  3. 执行HttpClient对象的execute方法,将Http请求对象作为该方法的参数。
  4. 读取execute方法返回的HttpResponse结果并解析。
  5. 释放连接。
public static String doPostToken(String tokenUrl,String clientId,String clientSecret,String grantType) {

    CloseableHttpResponse response = null;
    String resultToken = "";
    try {
        //1.创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //2.创建Http Post请求
        HttpPost httpPost = new HttpPost(tokenUrl);

        //3.封装请求参数
        List<BasicNameValuePair> list = new ArrayList<>();
        list.add(new BasicNameValuePair("client_id", clientId));
        list.add(new BasicNameValuePair("client_secret", clientSecret));
        list.add(new BasicNameValuePair("grant_type", grantType));
        httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));

        //4.执行http请求
        response = httpClient.execute(httpPost);
        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK ){

            JSONObject jsonObject = JSONObject.fromObject(EntityUtils.toString(response.getEntity(), "utf-8"));
            resultToken = (String) Optional.ofNullable(jsonObject.get("access_token")).orElseGet(String::new);
        }else{
            resultToken = "";
        }
    } catch (Exception e) {
        LOG.error("post request get Token ERR XXXXXXXXXXXXXXXXX"+e);
    }finally {
        try {
            response.close();
        } catch (IOException e) {
            LOG.error("post request get Token close ERR XXXXXXXXXXXXXXXXX"+e);
        }
    }
    return resultToken;
}

环境说明:JDK1.8、SpringBoot

准备环节

第一步:在pom.xml中引入HttpClient的依赖
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>
第二步:引入fastjson依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.78</version>
</dependency>

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

详细使用示例

声明:此示例中,以JAVA发送HttpClient(在test里面单元测试发送的);也是以JAVA接收的(在controller里面接收的)

GET无参

你有没有想过,你平时是如何来访问百度的呢?是不是得遵循下面三个步骤呢:

  • 第一步,打开浏览器
  • 第二步,在浏览器地址栏中输入url,例如www.baidu.com
  • 第三步,按回车键,发出请求

使用HttpClient模拟浏览器发送请求,并接收服务端返回的响应

alt

HttpClient发送示例:
@Test
public void doGetTestOne() {
    // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    // 创建get请求
    HttpGet httpGet = new HttpGet("http://127.0.0.1:8080/doGetControllerOne");
    // 响应模型
    CloseableHttpResponse response = null;
    try {
        // 由Http客户端执行(发送)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));
        }
    } catch (ParseException | IOException e) {
        e.printStackTrace();
    } finally {
        try {
            // 释放资源
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
对应接收示例:
/**
     * Get无参
     *
     * @return 测试数据
     */
@GetMapping("/doGetControllerOne")
public String doGetControllerOne() {
    return "123";
}
结果

记得首先运行启动类!

alt

GET有参(方式一:直接拼接URL):
HttpClient发送示例:
/**
     * GET---有参测试 (方式一:手动在url后面加上参数)
     */
@Test
public void doGetTestWayOne() {
    // 获得Http客户端
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    // 参数
    StringBuffer params = new StringBuffer();
    // 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
    try {
        params.append("name=" + URLEncoder.encode("&", "utf-8"));
        params.append("&");
        params.append("age=24");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    // 创建Get请求
    HttpGet httpGet = new HttpGet("http://127.0.0.1:8080/doGetControllerTwo" + "?" + 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));
        }
    } catch (IOException | ParseException e) {
        e.printStackTrace();
    } finally {
        try {
            // 释放资源
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
对应接收示例:
/**
     * Get有参(直接拼接URL)
     * @param name 姓名
     * @param age 年龄
     * @return 测试数据
     */
@GetMapping("/doGetControllerTwo")
public String doGetControllerTwo(String name, Integer age) {
    return "没想到[" + name + "]都" + age + "岁了!";
}
GET有参(方式二:使用URI获得HttpGet):
HttpClient发送示例:
/**
     * GET---有参测试 (方式二:将参数放入键值对类中,再放入URI中,从而通过URI得到HttpGet实例)
     */
@Test
public void doGetTestWayTwo() {
    // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    // 参数
    URI uri = null;
    // 将参数放入键值对类NameValuePair中,再放入集合中
    // 建立一个NameValuePair数组,用于存储欲传送的参数
    ArrayList<NameValuePair> params = new ArrayList<>();
    // 添加参数
    params.add(new BasicNameValuePair("name", "&"));
    params.add(new BasicNameValuePair("age", "18"));
    // 设置uri信息,并将参数集合放如入uri
    // 注:这里也支持一个键值对。一个键值对往里面放setParameter(String key, String value)
    try {
        uri = new URIBuilder().setScheme("http").setHost("127.0.0.1")
            .setPort(8080).setPath("/doGetControllerThird")
            .setParameters(params).build();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    // 创建Http请求
    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));
        }
    } catch (ParseException | IOException e) {
        e.printStackTrace();
    } finally {
        try {
            // 释放资源
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
对应接收示例:
@GetMapping("/doGetControllerThird")
public String doGetControllerThird(String name, Integer age) {
    return "没想到[" + name + "]都" + age + "岁了!";
}
POST无参:
HttpClient发送示例:
/**
 * POST---无参测试
*/
@Test
public void doPostTestOne() {
    // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    // 创建Post请求
    HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/doPostControllerOne");
    // 响应模型
    CloseableHttpResponse response = null;
    try {
        // 由客户端执行(发送)Post请求
        response = httpClient.execute(httpPost);
        // 从响应模型中获取响应实体
        HttpEntity responseEntity = response.getEntity();
        System.out.println("响应状态为:" +a response.getStatusLine());
        if (responseEntity != null) {
            System.out.println("响应内容长度为:" + responseEntity.getContentLength());
            System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
        }
    } catch (ParseException | IOException e) {
        e.printStackTrace();
    } finally {
        try {
            // 释放资源
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
对应接收示例:
/**
* Post无参
*
* @return 测试数据
*/
@PostMapping("/doPostControllerOne")
public String doPostControllerOne() {
    return "这个post请求没有任何参数!";
}
POST有参(普通参数):

注:POST传递普通参数时,方式与GET一样即可,这里以直接在url后缀上参数的方式示例。

/**
     * POST---有参测试(普通参数)
     */
@Test
public void doPostTestTwo() {
    // 获取Http客户端
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    // 参数
    StringBuffer params = new StringBuffer();
    try {
        params.append("name=" + URLEncoder.encode("&", "utf-8"));
        params.append("&");
        params.append("age=24");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    // 创建Post请求
    HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/doPostControllerTwo" + "?" + 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));
        }
    } catch (ParseException | IOException e) {
        e.printStackTrace();
    } finally {
        try {
            // 释放资源
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
对应接收示例:
/**
* Post有参(普通参数)
* @param name 姓名
* @param age 年龄
* @return 测试数据
*/
@PostMapping("/doPostControllerTwo")
public String doPostControllerTwo(String name, Integer age) {
    return "没想到[" + name + "]都" + age + "岁了!";
}
POST有参(对象参数):
先给出User类:
@Data
public class User {

    private Integer id;
    private String username;
    private String password;
    private String nickName;
    private Integer age;
    private String sex;
    private String address;
    private Integer role;
    private String avatar;
    private double account;

    @Override
    public String toString() {
        return id + "号" + username + "的昵称是 " + nickName + ",密码是" + password + "今年" + age + "岁 " + "性别:" + sex + " 地址:" + address + " 扮演角色:" + role + "头像:" + avatar + "账户:" + account;
    }
}
HttpClient发送示例:
@Test
public void doPostTestThird() {
    // 获得Http客户端
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    // 创建Post请求
    HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/doPostControllerThird");
    User user = new User();
    user.setId(1);
    user.setUsername("莱维");
    user.setPassword("216017");
    user.setNickName("levy");
    user.setAge(18);
    user.setSex("女");
    user.setAddress("宇宙");
    user.setRole(1);
    user.setAvatar("1999");
    user.setAccount(100000);
    // 这里利用阿里的fastjson,将Object转换为json字符串
    String jsonString = JSON.toJSONString(user);
    // 创建具有指定内容和字符集的 StringEntity,从String获得实体内容
    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));
        }
    } catch (ParseException | IOException e) {
        e.printStackTrace();
    } finally {
        try {
            // 释放资源
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
对应接收示例:
@PostMapping("/doPostControllerThird")
public String doPostControllerThird(@RequestBody User user) {
    return user.toString();
}
POST有参(普通参数 + 对象参数):

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

先给出User类:
@Data
public class User {

    private Integer id;
    private String username;
    private String password;
    private String nickName;
    private Integer age;
    private String sex;
    private String address;
    private Integer role;
    private String avatar;
    private double account;

    @Override
    public String toString() {
        return id + "号" + username + "的昵称是 " + nickName + ",密码是" + password + "今年" + age + "岁 " + "性别:" + sex + " 地址:" + address + " 扮演角色:" + role + "头像:" + avatar + "账户:" + account;
    }
}
HttpClient发送示例:
@Test
public void doPostTestFour() {
    // 获的Http客户端
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    // 参数
    URI uri = null;
    try {
        // 将参数放入键值对类NameValuePair中,再放入集合中
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("flag", "4"));
        params.add(new BasicNameValuePair("meaning", "记录员"));
        // 设置uri信息,并将参数集合放入uri;
        // 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value)
        uri = new URIBuilder().setScheme("http").setHost("127.0.0.1").setPort(8080).setPath("/doPostControllerFour").setParameters(params).build();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    // 创建Post请求
    HttpPost httpPost = new HttpPost(uri);
    // 创建User参数
    User user = new User();
    user.setId(2);
    user.setUsername("唐欧");
    user.setPassword("13457");
    user.setNickName("to");
    user.setAge(18);
    user.setSex("女");
    user.setAddress("太阳");
    user.setRole(2);
    user.setAvatar("2002");
    user.setAccount(50000);
    // 将User对象转换为json字符串,并放入entity中
    StringEntity stringEntity = new StringEntity(JSON.toJSONString(user), "utf-8");
    // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
    httpPost.setEntity(stringEntity);
    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));
        }
    } catch (ParseException | IOException e) {
        e.printStackTrace();
    } finally {
        try {
            // 释放资源
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
对应接收示例:
@PostMapping("/doPostControllerFour")
public String doPostControllerFour(@RequestBody User user, Integer flag, String meaning) {
    return user.toString() + "\n" + flag + ">>>" + meaning;
}
解决响应乱码问题(示例):

alt

出现的问题

在HttpClient请求的时候,返回结果解析时出现java.io.IOException: Attempted read from closed stream.异常。

原因是EntityUtils.toString(HttpEntity)方法被使用了多次。所以每个方法内只能使用一次!

entity所得到的流是不可重复读取的,也就是说所得的到实体只能一次消耗完,不能多次读取。

解决办法:

方案一: 进行两次请求。

代码不举例子。

方案二:首先保存流数据,再通过流 reset方法重置游标。

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(paramList, Consts.UTF_8));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();

InputStream in = entity.getContent();//获取数据流

// 保存流
ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
BufferedInputStream br = new BufferedInputStream(in); 
byte[] b = new byte[1024]; 
for (int c = 0; (c = br.read(b)) != -1;) 
{ 
    bos.write(b, 0, c); 
} 
b = null; 
br.close(); 


in = new ByteArrayInputStream(bos.toByteArray());
// 第一次读流
StringBuffer out = new StringBuffer();
byte[] b1 = new byte[1024]; 
for (int n; (n = in.read(b1)) != -1;) {
    out.append(new String(b1, 0, n));  //这个可以用来读取文件内容 并且文件内容有中文读取出来也不会乱码
}
// 判断文件是否存在
String resultHtml = out.toString();
int firstIndex = resultHtml.indexOf("\n");
if(firstIndex < 0){
    logger.info("文件不存在或异常"+resultHtml);
    return false;
}
// 重置游标
in.reset();

// 输出到文件
FileOutputStream fos = new FileOutputStream(new File(req.getFilePath()));
BufferedOutputStream  bos1 = new BufferedOutputStream(fos,2048);
// 第二次读流
int len;
byte [] bytes = new byte[2048];
while((len=in.read(bytes,0,2048)) != -1){
    bos1.write(bytes,0,len);
}
bos1.flush();
bos1.close();
进行HTTPS请求并进行(或不进行)证书校验(示例):
使用示例:

alt

相关方法详情(非完美封装):
/**
 * 根据是否是https请求,获取HttpClient客户端
 *
 * TODO 本人这里没有进行完美封装。对于 校不校验校验证书的选择,本人这里是写死
 *      在代码里面的,你们在使用时,可以灵活二次封装。
 *
 * 提示: 此工具类的封装、相关客户端、服务端证书的生成,可参考我的这篇博客:
 *      <linked>https://blog.csdn.net/justry_deng/article/details/91569132</linked>
 *
 *
 * @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;
}
application/x-www-form-urlencoded表单请求(示例):

alt

发送文件(示例):
准备工作:

如果想要灵活方便的传输文件的话,除了引入org.apache.httpcomponents基本的httpclient依赖外再额外引入org.apache.httpcomponents的httpmime依赖。

即便不引入httpmime依赖,也是能传输文件的,不过功能不够强大。

在pom.xml中额外引入:

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.13</version>
</dependency>
发送端是这样的:
/**
 *
 * 发送文件
 *
 * multipart/form-data传递文件(及相关信息)
 *
 * 注:如果想要灵活方便的传输文件的话,
 *    除了引入org.apache.httpcomponents基本的httpclient依赖外
 *    再额外引入org.apache.httpcomponents的httpmime依赖。
 *    追注:即便不引入httpmime依赖,也是能传输文件的,不过功能不够强大。
 *
 */
@Test
public void test4() {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost httpPost = new HttpPost("http://localhost:12345/file");
    CloseableHttpResponse response = null;
    try {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        // 第一个文件
        String filesKey = "files";
        File file1 = new File("C:\\Users\\JustryDeng\\Desktop\\back.jpg");
        multipartEntityBuilder.addBinaryBody(filesKey, file1);
        // 第二个文件(多个文件的话,使用同一个key就行,后端用数组或集合进行接收即可)
        File file2 = new File("C:\\Users\\JustryDeng\\Desktop\\头像.jpg");
        // 防止服务端收到的文件名乱码。 我们这里可以先将文件名URLEncode,然后服务端拿到文件名时在URLDecode。就能避免乱码问题。
        // 文件名其实是放在请求头的Content-Disposition里面进行传输的,如其值为form-data; name="files"; filename="头像.jpg"
        multipartEntityBuilder.addBinaryBody(filesKey, file2, ContentType.DEFAULT_BINARY, URLEncoder.encode(file2.getName(), "utf-8"));
        // 其它参数(注:自定义contentType,设置UTF-8是为了防止服务端拿到的参数出现乱码)
        ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
        multipartEntityBuilder.addTextBody("name", "邓沙利文", contentType);
        multipartEntityBuilder.addTextBody("age", "25", contentType);

        HttpEntity httpEntity = multipartEntityBuilder.build();
        httpPost.setEntity(httpEntity);

        response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        System.out.println("HTTPS响应状态为:" + response.getStatusLine());
        if (responseEntity != null) {
            System.out.println("HTTPS响应内容长度为:" + responseEntity.getContentLength());
            // 主动设置编码,来防止响应乱码
            String responseStr = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            System.out.println("HTTPS响应内容为:" + responseStr);
        }
    } catch (ParseException | IOException e) {
        e.printStackTrace();
    } finally {
        try {
            // 释放资源
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
接收端是这样的:

alt

发送流(示例):
发送端是这样的:
/**
 *
 * 发送流
 *
 */
@Test
public void test5() {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost httpPost = new HttpPost("http://localhost:12345/is?name=邓沙利文");
    CloseableHttpResponse response = null;
    try {
        InputStream is = new ByteArrayInputStream("流啊流~".getBytes());
        InputStreamEntity ise = new InputStreamEntity(is);
        httpPost.setEntity(ise);

        response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        System.out.println("HTTPS响应状态为:" + response.getStatusLine());
        if (responseEntity != null) {
            System.out.println("HTTPS响应内容长度为:" + responseEntity.getContentLength());
            // 主动设置编码,来防止响应乱码
            String responseStr = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            System.out.println("HTTPS响应内容为:" + responseStr);
        }
    } catch (ParseException | IOException e) {
        e.printStackTrace();
    } finally {
        try {
            // 释放资源
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
接收端是这样的:

alt

工具类提示:

使用HttpClient时,可以视情况将其写为工具类。

如:Github上Star非常多的一个HttpClient的工具类是httpclientutil。

本人在这里也推荐使用该工具类,因为该工具类的编写者封装了很多功能在里面,如果不是有什么特殊的需求的话,完全可以不用造轮子,可以直接使用。

测试demo,原生HttpClient使用

新建HttpClientGetTest.java测试类,测试get请求
public static void main(String[] args) throws IOException {
    //1.打开浏览器
    CloseableHttpClient httpClient = HttpClients.createDefault();
    //2.声明get请求
    HttpGet httpGet = new HttpGet("http://www.baidu.com/s?wd=java");
    //3.发送请求
    CloseableHttpResponse response = httpClient.execute(httpGet);
    //4.判断状态码
    if(response.getStatusLine().getStatusCode()==200){
        HttpEntity entity = response.getEntity();
        //使用工具类EntityUtils,从响应中取出实体表示的内容并转换成字符串
        String string = EntityUtils.toString(entity, "utf-8");
        System.out.println(string);
    }
    //5.关闭资源
    response.close();
    httpClient.close();
}
新建HttpClientPostTest.java测试类,测试post请求
public static void main(String[] args) throws IOException {
    //1.打开浏览器
    CloseableHttpClient httpClient = HttpClients.createDefault();
    //2.声明get请求
    HttpPost httpPost = new HttpPost("https://www.oschina.net/");
    //3.开源中国为了安全,防止恶意攻击,在post请求中都限制了浏览器才能访问
    httpPost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
    //4.判断状态码
    List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
    parameters.add(new BasicNameValuePair("scope", "project"));
    parameters.add(new BasicNameValuePair("q", "java"));

    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,"UTF-8");

    httpPost.setEntity(formEntity);

    //5.发送请求
    CloseableHttpResponse response = httpClient.execute(httpPost);

    if(response.getStatusLine().getStatusCode()==200){
        HttpEntity entity = response.getEntity();
        String string = EntityUtils.toString(entity, "utf-8");
        System.out.println(string);
    }
    //6.关闭资源
    response.close();
    httpClient.close();
}

初始化httpClient的几种方式

:one: CloseableHttpClient httpclient = HttpClients.createDefault();

:two: DefaultHttpClient client = new DefaultHttpClient(new PoolingClientConnectionManager());

:three: HttpClient httpclient = HttpClients.createDefault();

HttpClient 远程接口调用

执行GET请求
/**
     * 执行Get请求
     */
public static void doGet() {
    // 设置UA字段(对照UA字串的标准格式理解一下每部分的意思),然后再创建HttpClient对象
    HttpClients.custom().setUserAgent("Mozilla/5.0(Windows;U;Windows NT 5.1;en-US;rv:0.9.4)");
    // 创建HttpClient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 创建HttpGet请求
    HttpGet httpGet = new HttpGet("https://www.baidu.com/");
    // 创建响应模型
    CloseableHttpResponse response = null;
    try {
        // HttpClient客户端执行Get请求
        response = httpClient.execute(httpGet);
        // 从响应模型中获取响应实体
        HttpEntity responseEntity = response.getEntity();
        System.out.println("响应状态为:" + response.getStatusLine());
        // 判断响应状态是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            String content = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            System.out.println("响应内容为:" + content);
            System.out.println("响应内容长度为:" + content.length());
        }
    } catch (ParseException | IOException e) {
        e.printStackTrace();
    } finally {
        try {
            // 释放资源
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
HttpClient访问返回403 forbiddent
直接创建HttpClient对象
// 创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();

这段代码会产生一个403 forbidden,原因是User-Agent字段存在问题,我们需要设置UA字段。UA就是浏览器身份的标识。

最关键的是因为没有设置为浏览器形式,被对方的nginx给拦截了所以才导致这种情况。

User-Agent是Http协议中的一部分,属于头域的组成部分,User Agent也简称UA。

  • 用较为普通的一点来说,是一种向访问网站提供你所使用的浏览器类型、操作系统及版本、CPU 类型、浏览器渲染引擎、浏览器语言、浏览器插件等信息的标识。UA字符串在每次浏览器 HTTP 请求时发送到服务器!

浏览器UA 字串的标准格式为: 浏览器标识 (操作系统标识; 加密等级标识; 浏览器语言) 渲染引擎标识 版本信息

解决办法

:one:第一种

// 设置UA字段(对照UA字串的标准格式理解一下每部分的意思),然后再创建HttpClient对象
HttpClients.custom().setUserAgent("Mozilla/5.0(Windows;U;Windows NT 5.1;en-US;rv:0.9.4)");
// 创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpGet请求
HttpGet httpGet = new HttpGet("https://www.baidu.com/");
// ......

:two:第二种

URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
    resultString = EntityUtils.toString(response.getEntity(), Encoding);
}
/**
    *	HttpPost request = new HttpPost(uri);
    *	request.setHeader( “User-Agent” ,“Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0” ); // 设置请求头
    request.setEntity(new UrlEncodedFormEntity(formParams, encoding));
*/

然后再使用创建出来的对象httpClient。