HttpClient简介

HttpClient是基于HttpCore的HTTP/1.1兼容的HTTP代理实现。 它还为客户端认证,HTTP状态管理和HTTP连接管理提供可重用组件。 HttpComponents Client是Commons HttpClient 3.x的继任者和替代者。 强烈建议Commons HttpClient的用户进行升级。

HttpClient HTTP Get请求

/**
* httpClient Get请求
*/
public static void main(String[] args) throws IOException {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) { //第一步 配置 Get 请求 Url
HttpGet httpget = new HttpGet("http://httpbin.org/get"); //第二步 创建一个自定义的 response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
}; //第三步 执行请求
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
}
}

HttpClient HTTP Post请求

/**
* httpClient Post请求
*/
public static void main(String[] args) throws IOException { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { //第一步 配置 Post 请求 Url
HttpPost httpPost = new HttpPost("http://httpbin.org/post"); // 装配post请求参数
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("age", "20")); //请求参数
list.add(new BasicNameValuePair("name", "zhangsan")); //请求参数
httpPost.setEntity(new StringEntity("Hello, World")); /*
设置post请求参数
两个方式:具体参考UrlEncodedFormEntity和StringEntity区别
*/
httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
//httpPost.setEntity(new StringEntity(list.toString(), "UTF-8")); //第二步 创建一个自定义的 response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
}; //第三步 执行请求
String responseBody = httpclient.execute(httpPost, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
}
}

HttpClient HTTP Put请求

/**
* httpClient Put 请求
*/
public static void main(String[] args) throws IOException { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { //第一步 配置 Post 请求 Url
HttpPut httpPut = new HttpPut("http://httpbin.org/put"); //设置post请求参数
httpPut.setEntity(new StringEntity("Hello, World")); //第二步 创建一个自定义的 response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
}; String responseBody = httpclient.execute(httpPut, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
} }

HttpClient HTTP Delete请求

/**
* httpClient Delete 请求
*/
public static void main(String[] args) throws IOException { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { //第一步 配置 Delete 请求 Url
HttpDelete httpDelete = new HttpDelete("http://httpbin.org/delete"); System.out.println("Executing request " + httpDelete.getRequestLine()); //第二步 创建一个自定义的 response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
}; String responseBody = httpclient.execute(httpDelete, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
}
}

HttpClient自定义HTTP Header

/**
* HttpClient自定义HTTP头
*/
public static void main(String[] args)throws IOException {
// 创建自定义 http headers
List<Header> defaultHeaders = Arrays.asList(
new BasicHeader("X-Default-Header", "default header httpclient")); // 设置自定义 http headers
CloseableHttpClient httpclient = HttpClients
.custom()
.setDefaultHeaders(defaultHeaders)
.build(); try { // 配置超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) //设置连接超时时间
.setConnectionRequestTimeout(5000) // 设置请求超时时间
.setSocketTimeout(5000)
.setRedirectsEnabled(true)//默认允许自动重定向
.build(); // 创建自定义 http headers on the http request
HttpUriRequest request = RequestBuilder.get()
.setUri("http://httpbin.org/headers")
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.setHeader(HttpHeaders.FROM, "https://memorynotfound.com")
.setHeader("X-Custom-Header", "custom header http request")
.setConfig(requestConfig)
.build(); System.out.println("Executing request " + request.getRequestLine()); // 创建自定义 response handler
ResponseHandler<String> responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
String responseBody = httpclient.execute(request, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
} finally {
httpclient.close();
}
}

更详细HttpClient 学习

教程参考:https://www.yiibai.com/httpclient/httpclient-overview.html (本文学习笔记)

Api参考:http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/

github代码:https://github.com/YoCiyy/HttpClientDemo

HttpClient 入门教程学习的更多相关文章

  1. Webpack新手入门教程(学习笔记)

    p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; text-align: center; font: 30.0px Helvetica; color: #000000 } ...

  2. .NetCore微服务Surging新手傻瓜式 入门教程 学习日志---先让程序跑起来(一)

    原文:.NetCore微服务Surging新手傻瓜式 入门教程 学习日志---先让程序跑起来(一) 写下此文章只为了记录Surging微服务学习过程,并且分享给广大想学习surging的基友,方便广大 ...

  3. .NetCore微服务Surging新手傻瓜式 入门教程 学习日志---结构简介(二)

    原文:.NetCore微服务Surging新手傻瓜式 入门教程 学习日志---结构简介(二) 先上项目解决方案图: 以上可以看出项目结构可以划分为4大块,1是surging的核心底层,2,3,4都可以 ...

  4. TypeScript 入门教程学习笔记

    TypeScript 入门教程学习笔记 1. 数据类型定义 类型 实例 说明 Number let num: number = 1; 基本类型 String let myName: string = ...

  5. Git 极简入门教程学习笔记

    Git 极简入门教程  http://rogerdudler.github.io/git-guide/index.zh.html 测试用 https://github.com/xxx/BrnShop. ...

  6. HttpClient入门教程

    HttpClient使用详解与实战一:https://www.jianshu.com/p/375be5929bed

  7. Latex 入门教程

    Latex 入门教程 学习途径:LaTex入门_哔哩哔哩_bilibili 运行环境:texlive2021.texstudio-4.1.2-win-qt6 1. 基本结构 整个 Latex 文件分为 ...

  8. 【特别推荐】Node.js 入门教程和学习资源汇总

    这篇文章与大家分享一批很有用的 Node.js 入门教程和学习资源.Node 是一个服务器端的 JavaScript 解释器,它将改变服务器应该如何工作的概念.它的目标是帮助程序员构建高度可伸缩的应用 ...

  9. C#入门教程(一)–.Net平台技术介绍、C#语言及开发工具介绍-打造C#学习教程

    一.什么是.Net平台? .Net平台是微软搭建的技术平台,技术人员在此平台上进行应用的搭建与开发.它提供了运行所必须的环境.NET Framework类库以及CLR(公共语言运行时).好比我们人类的 ...

随机推荐

  1. Notepad++给自己打造一款PowerQuery M语言编辑器【转】

    Excel 使用Notepad++给自己打造一款PowerQuery M语言编辑器 Excel 使用Notepad++给自己打造一款PowerQuery M语言编辑器-Power BI-ExcelHo ...

  2. OCP 12c最新考试原题及答案(071-3)

    3.(4-10) choose the best answer:The user SCOTT who is the owner of ORDERS and ORDER_ITEMS tables iss ...

  3. “全栈2019”Java第二十二章:控制流程语句中的决策语句if-else

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...

  4. [ActionScript 3.0] AS3 socket示例(官方示例)

    下例对套接字执行读写操作,并输出在套接字事件期间传输的信息. 该示例的要点遵循: 该构造函数创建名为 socket 的 CustomSocket 实例,并将主机名 localhost 和端口 80 作 ...

  5. Ionic2 快速入门

    本文原创版权归 博客园 yan_xiaodi 所有,转载请自觉于篇头位置显示标明原创作者及出处,这是您对作者劳动果实的自觉尊重!! 作者:yan_xiaodi 原文:http://www.cnblog ...

  6. curl命令上传下载文件

    下载单个文件,默认将输出打印到标准输出中(STDOUT)中 curl http://www.centos.org 通过-o/-O选项保存下载的文件到指定的文件中: -o:将文件保存为命令行中指定的文件 ...

  7. 利用腾讯云为你的域名申请并配置免费SSL一年

    我想,点进来的朋友,应该都知道SSL的重要性吧.这里就简单提一下,大型网站域名只有配置了SSL后,才会更加安全. 现在,微信小程序也开始要求后台必须是SSL配置后的域名了.说了这么多,估计有些人还是有 ...

  8. 世界最大BT服务器本周死了三回 海盗湾要凉凉?

    想當初,我是受到BT網站海盜灣的啟發,開發了一個DHT下載網站:http://www.ibmid.com,有一段時間通宵編程,理解此個協議. 海盗湾(The Pirate Bay)是世界上最大的 BT ...

  9. js控制a标签点击事件 触发下载

    问题背景,动态获取data把url赋值到a标签的url中,让a标签自动下载 首先想到的应该是$('xxx').click(), 查资料明白:js中的$(...).click()事件只能触发绑定的onC ...

  10. 性能调优之vmstat命令(转)

    vmstat是Virtual Meomory Statistics(虚拟内存统计)的缩写,可对操作系统的虚拟内存.进程.IO读写.CPU活动等进行监视.它是对系统的整体情况进行统计,不足之处是无法对某 ...