HttpClient是支持Http协议的客户端编程工具包。

一、简单使用

1.1 引入依赖


<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>

1.2 一个简单的Get请求


public static void main(String[] args) {
//创建HttpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建HttpGet实例
HttpGet httpGet = new HttpGet("http://www.baidu.com");
CloseableHttpResponse response = null;
//执行Get请求
try {
response = httpClient.execute(httpGet);
//获取实体
HttpEntity httpEntity = response.getEntity();
//解析实体
System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
} }

1.3 Post请求、请求头、请求参数

1.4 使用代理

1.5 设置超时时间

HttpClient内部有三个超时时间设置:连接池获取可用连接超时,连接超时,读取数据超时

先连接,后读取。

RequestConfig requestConfig = RequestConfig.custom()
//从连接池中获取连接的超时时间
.setConnectTimeout(5000)
//httpclient会创建一个异步线程用以创建socket连接,此处设置该socket的连接超时时间
.setConnectionRequestTimeout(1000)
//socket读数据超时时间:从服务器获取响应数据的超时时间
.setSocketTimeout(5000)
.build();
httpGet.setConfig(requestConfig);

参考文档

HttpClient源码解析系列:第二篇:极简版实现

HttpClient官网 Quick Start

参考视频

一头扎进HttpClient

最新文章

  1. Webpack+React+ES6开发模式入门指南
  2. MVP社区巡讲-云端基础架构:12月5日北京站 12月12日上海站
  3. Python2 新手 编码问题 吐血总结
  4. Android之SqlLite数据库使用
  5. ORACLE Linux以及 Unbreakable Enterprise Kernel
  6. C和指针 第七章 可变参数
  7. python学习道路(day10note)(线程,进程)
  8. Linux配置notes
  9. 脉冲计数功能在ESM335x-Linux主板上的实现
  10. 理解React中es6方法创建组件的this
  11. I/O Completions port
  12. sentos nginx安装
  13. Intellij Idea 13 vmoptions (Mac版本)
  14. JS年月日三级联动下拉框日期选择代码
  15. hdu 1533 Going Home 最小费用流
  16. 十二个 ASP.NET Core 例子——中间件
  17. 多个yml文件的读取方式
  18. iOS 中的block异常 判断block是否为空
  19. Python 缓存服务
  20. ASP.NET Core 1.0 基础与应用启动

热门文章

  1. Fortify漏洞之Path Manipulation(路径篡改)
  2. K2 BPM_当K2遇上医药,用流程打通企业的任督二脉_业务流程管理系统
  3. PL/SQL Developer_如何快速获得表名或全部列名的文本形式
  4. WebService 规范
  5. 四、DDL常见操作汇总
  6. Django 中使用权限认证
  7. Vue 前后端分离系统中遇到跨域问题
  8. java学习(1) ----getMethod()和getDeclaredMethod()的区别(转)
  9. linux网络编程之简单的线程池实现
  10. evpp return index.html