HttpClient学习(一)—— 基本使用
2024-08-27 00:32:47
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
参考视频
最新文章
- Webpack+React+ES6开发模式入门指南
- MVP社区巡讲-云端基础架构:12月5日北京站 12月12日上海站
- Python2 新手 编码问题 吐血总结
- Android之SqlLite数据库使用
- ORACLE Linux以及 Unbreakable Enterprise Kernel
- C和指针 第七章 可变参数
- python学习道路(day10note)(线程,进程)
- Linux配置notes
- 脉冲计数功能在ESM335x-Linux主板上的实现
- 理解React中es6方法创建组件的this
- I/O Completions port
- sentos nginx安装
- Intellij Idea 13 vmoptions (Mac版本)
- JS年月日三级联动下拉框日期选择代码
- hdu 1533 Going Home 最小费用流
- 十二个 ASP.NET Core 例子——中间件
- 多个yml文件的读取方式
- iOS 中的block异常 判断block是否为空
- Python 缓存服务
- ASP.NET Core 1.0 基础与应用启动
热门文章
- Fortify漏洞之Path Manipulation(路径篡改)
- K2 BPM_当K2遇上医药,用流程打通企业的任督二脉_业务流程管理系统
- PL/SQL Developer_如何快速获得表名或全部列名的文本形式
- WebService 规范
- 四、DDL常见操作汇总
- Django 中使用权限认证
- Vue 前后端分离系统中遇到跨域问题
- java学习(1) ----getMethod()和getDeclaredMethod()的区别(转)
- linux网络编程之简单的线程池实现
- evpp return index.html