一 HttpClient简介
1.1 概述
HttpClient只能以编程的方式通过其API用于传输和接受HTTP消息。主要实现功能:
实现了所有 HTTP 的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)
支持 HTTPS 协议
支持代理服务器(Nginx等)等
支持自动(跳转)转向。
1.2 案例工程介绍
1.2.1 工程截图
请求端:16-spt-http-request-demo :7000 响应端:16-spt-httppush-demo :8082
1.2.2 引入依赖
<!-- httpclient --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.5</version></dependency><!-- fastjson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version></dependency>
注:SpringBoot的基本依赖配置,这里就不再多说了
二 实操实例Get方式
2.1 get无参数案例
1.消费者
@RestController
public class HttpClientController {@RequestMapping("/hc/api")public String getInfo() throws Exception {
// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)CloseableHttpClient httpClient = HttpClientBuilder.create().build();// 创建Get请求HttpGet httpGet = new HttpGet("http://localhost:8082/get/noparam");String result="";// 响应模型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());result=EntityUtils.toString(responseEntity);System.out.println("响应内容为:" + result);}} 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();}}return result;}
}
2.服务者
@RestController
public class HttpClientController {@RequestMapping("/get/noparam")public String doGetNoParam(){return "ok 123!";}
}
截图如下:
3.请求测试