HttpClient使用介绍
使用HttpClient发送请求主要分为以下几步骤:

创建 CloseableHttpClient对象或CloseableHttpAsyncClient对象,前者同步,后者为异步

创建Http请求对象

调用execute方法执行请求,如果是异步请求在执行之前需调用start方法

创建连接:

CloseableHttpClient httpClient = HttpClientBuilder.create().build();
该连接为同步连接

GET请求:

@Test
public void testGet() throws IOException {
String api = "/api/files/1";
String url = String.format("%s%s", BASE_URL, api);
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
System.out.println(EntityUtils.toString(response.getEntity()));
}
使用HttpGet表示该连接为GET请求,HttpClient调用execute方法发送GET请求

PUT请求:

@Test
public void testPut() throws IOException {
String api = "/api/user";
String url = String.format("%s%s", BASE_URL, api);
HttpPut httpPut = new HttpPut(url);
UserVO userVO = UserVO.builder().name("h2t").id(16L).build();
httpPut.setHeader("Content-Type", "application/json;charset=utf8");
httpPut.setEntity(new StringEntity(JSONObject.toJSONString(userVO), "UTF-8"));
CloseableHttpResponse response = httpClient.execute(httpPut);
System.out.println(EntityUtils.toString(response.getEntity()));
}
POST请求:

添加对象

@Test
public void testPost() throws IOException {
String api = "/api/user";
String url = String.format("%s%s", BASE_URL, api);
HttpPost httpPost = new HttpPost(url);
UserVO userVO = UserVO.builder().name("h2t2").build();
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
httpPost.setEntity(new StringEntity(JSONObject.toJSONString(userVO), "UTF-8"));
CloseableHttpResponse response = httpClient.execute(httpPost);
System.out.println(EntityUtils.toString(response.getEntity()));
}
该请求是一个创建对象的请求,需要传入一个json字符串

上传文件

@Test
public void testUpload1() throws IOException {
String api = "/api/files/1";
String url = String.format("%s%s", BASE_URL, api);
HttpPost httpPost = new HttpPost(url);
File file = new File("C:/Users/hetiantian/Desktop/学习/docker_practice.pdf");
FileBody fileBody = new FileBody(file);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("file", fileBody); //addPart上传文件
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
System.out.println(EntityUtils.toString(response.getEntity()));
}

通过addPart上传文件

DELETE请求:

@Test
public void testDelete() throws IOException {
String api = "/api/user/12";
String url = String.format("%s%s", BASE_URL, api);
HttpDelete httpDelete = new HttpDelete(url);
CloseableHttpResponse response = httpClient.execute(httpDelete);
System.out.println(EntityUtils.toString(response.getEntity()));
}
请求的取消:

@Test
public void testCancel() throws IOException {
String api = "/api/files/1";
String url = String.format("%s%s", BASE_URL, api);
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig); //设置超时时间
//测试连接的取消

long begin = System.currentTimeMillis();
CloseableHttpResponse response = httpClient.execute(httpGet);
while (true) {
if (System.currentTimeMillis() - begin > 1000) {
httpGet.abort();
System.out.println("task canceled");
break;
}
}

System.out.println(EntityUtils.toString(response.getEntity()));
}

调用abort方法取消请求 执行结果:

task canceled
cost 8098 msc
Disconnected from the target VM, address: '127.0.0.1:60549', transport: 'socket'

java.net.SocketException: socket closed...【省略】

OkHttp使用

使用OkHttp发送请求主要分为以下几步骤:

创建OkHttpClient对象

创建Request对象

将Request 对象封装为Call

通过Call 来执行同步或异步请求,调用execute方法同步执行,调用enqueue方法异步执行

创建连接:

private OkHttpClient client = new OkHttpClient();
GET请求:

@Test
public void testGet() throws IOException {
String api = "/api/files/1";
String url = String.format("%s%s", BASE_URL, api);
Request request = new Request.Builder()
.url(url)
.get()
.build();
final Call call = client.newCall(request);
Response response = call.execute();
System.out.println(response.body().string());
}
PUT请求:

@Test
public void testPut() throws IOException {
String api = "/api/user";
String url = String.format("%s%s", BASE_URL, api);
//请求参数
UserVO userVO = UserVO.builder().name("h2t").id(11L).build();
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
JSONObject.toJSONString(userVO));
Request request = new Request.Builder()
.url(url)
.put(requestBody)
.build();
final Call call = client.newCall(request);
Response response = call.execute();
System.out.println(response.body().string());
}
POST请求:

添加对象

@Test
public void testPost() throws IOException {
String api = "/api/user";
String url = String.format("%s%s", BASE_URL, api);
//请求参数
JSONObject json = new JSONObject();
json.put("name", "hetiantian");
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), String.valueOf(json));
Request request = new Request.Builder()
.url(url)
.post(requestBody) //post请求
.build();
final Call call = client.newCall(request);
Response response = call.execute();
System.out.println(response.body().string());
}

上传文件

@Test
public void testUpload() throws IOException {
String api = "/api/files/1";
String url = String.format("%s%s", BASE_URL, api);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", "docker_practice.pdf",
RequestBody.create(MediaType.parse("multipart/form-data"),
new File("C:/Users/hetiantian/Desktop/学习/docker_practice.pdf")))
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody) //默认为GET请求,可以不写
.build();
final Call call = client.newCall(request);
Response response = call.execute();
System.out.println(response.body().string());
}

通过addFormDataPart方法模拟表单方式上传文件

DELETE请求:

@Test
public void testDelete() throws IOException {
String url = String.format("%s%s", BASE_URL, api);
//请求参数
Request request = new Request.Builder()
.url(url)
.delete()
.build();
final Call call = client.newCall(request);
Response response = call.execute();
System.out.println(response.body().string());
}
请求的取消:

@Test
public void testCancelSysnc() throws IOException {
String api = "/api/files/1";
String url = String.format("%s%s", BASE_URL, api);
Request request = new Request.Builder()
.url(url)
.get()
.build();
final Call call = client.newCall(request);
Response response = call.execute();
long start = System.currentTimeMillis();
//测试连接的取消
while (true) {
//1分钟获取不到结果就取消请求
if (System.currentTimeMillis() - start > 1000) {
call.cancel();
System.out.println("task canceled");
break;
}
}

System.out.println(response.body().string());
}
调用cancel方法进行取消 测试结果:

HttpClient超时设置:
在HttpClient4.3+版本以上,超时设置通过RequestConfig进行设置

private CloseableHttpClient httpClient = HttpClientBuilder.create().build();
private RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(60 * 1000)
.setConnectTimeout(60 * 1000).build();
String api = "/api/files/1";
String url = String.format("%s%s", BASE_URL, api);
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig); //设置超时时间
超时时间是设置在请求类型HttpGet上,而不是HttpClient上

OkHttp超时设置:
直接在OkHttp上进行设置

private OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)//设置连接超时时间
.readTimeout(60, TimeUnit.SECONDS)//设置读取超时时间
.build();
小结:
如果client是单例模式,HttpClient在设置超时方面来的更灵活,针对不同请求类型设置不同的超时时间,OkHttp一旦设置了超时时间,所有请求类型的超时时间也就确定

总结:

OkHttp和HttpClient在性能和使用上不分伯仲,根据实际业务选择即可。

httpclients 和 okhttp 区别的更多相关文章

  1. [Network] okhttp3与旧版本okhttp的区别分析

    cp from : https://www.jianshu.com/p/4a8c94b239b4 1.包名改变 包名改了由之前的 com.squareup.http.改为 okhttp3. 我们需要将 ...

  2. okhttp3与旧版本okhttp的区别分析

    https://www.jianshu.com/p/4a8c94b239b4  待总结学习

  3. okhttp教程——起步篇

    okhttp教程--起步篇 这篇文章主要总结Android著名网络框架-okhttp的基础使用,后续可能会有关于他的高级使用. okhttp是什么 okhttp是Android端的一个Http客户端, ...

  4. Android OkHttp完全解析 --zz

    参考文章 https://github.com/square/okhttp http://square.github.io/okhttp/ 泡网OkHttp使用教程 Android OkHttp完全解 ...

  5. Android OkHttp完全解析 是时候来了解OkHttp了

    Android OkHttp完全解析 是时候来了解OkHttp了 标签: AndroidOkHttp 2015-08-24 15:36 316254人阅读 评论(306) 收藏 举报  分类: [an ...

  6. 框架--NoHttp和OkHttp哪个好用,Volley和NoHttp哪个好用?

    NoHttp和OkHttp哪个好用,Volley和NoHttp哪个好用? NoHttp 源码及Demo托管在Github欢迎大家Star: https://github.com/Y0LANDA/NoH ...

  7. 论httpclient上传带参数【commons-httpclient和apache httpclient区别】

    需要做一个httpclient上传,然后啪啪啪网上找资料 1.首先以前系统中用到的了commons-httpclient上传,找了资料后一顿乱改,然后测试 PostMethod filePost = ...

  8. Android项目框架升级尝鲜OkHttp

    本文来自http://blog.csdn.net/liuxian13183/ ,引用必须注明出处! 随着项目日趋稳定,需求不再总是变化,那么是时间来整理下项目了.先简单介绍下,本项目最初使用loop4 ...

  9. [转] Android OkHttp完全解析 是时候来了解OkHttp了

    http://blog.csdn.net/lmj623565791/article/details/47911083: 本文出自:[张鸿洋的博客] 一.概述 最近在群里听到各种讨论okhttp的话题, ...

  10. 基于OkHttp的封装库TigerOkHttp的使用

    在前面熟悉了OkHttp的用法之后,为了简化用法同时适用于我的项目,我针对OkHttp进行了更进一步的封装(源码及其Demo地址在https://github.com/huyongli/TigerOk ...

随机推荐

  1. ros源的移除

    在Ubuntu上卸载了ros系统后,每次运行源更新命令 sudo apt update 都会报错,提示ros源找不到等问题. 这时,只需要 cd /etc/apt/souce.list.d sudo ...

  2. 《深入理解Java虚拟机》读书笔记:方法调用

      方法调用并不等同于方法执行,方法调用阶段唯一的任务就是确定被调用方法的版本(即调用哪一个方法),暂时还不涉及方法内部的具体运行过程.在程序运行时,进行方法调用是最普遍.最频繁的操作,但前面已经讲过 ...

  3. 【LaTeX】语法(更新中)

    目录 长度 空行 空格 超链接 数学公式 段落中(隐式) 单独成段(显式) 居中,左对齐,右对齐 居中 左对齐 右对齐 参考文献配置 TODO 参考资料 中文支持参考环境配置中的 内容,在这里不做重复 ...

  4. Go 并发编程 - runtime 协程调度(三)

    Go Runtime Go runtime 可以形象的理解为 Go 程序运行时的环境,类似于 JVM.不同于 JVM 的是,Go 的 runtime 与业务程序直接打包在一块,是一个可执行文件,直接运 ...

  5. 响应式编程——初识 Flux 和 Mono

    by emanjusaka from ​ https://www.emanjusaka.top/archives/4 彼岸花开可奈何 本文欢迎分享与聚合,全文转载请留下原文地址. 前言 Reactor ...

  6. 银河麒麟使用kickstart二次打包制作安装镜像ISO

    系统:银河麒麟 V10 SP2 服务器:百信恒山 TS02F-F30 安装方式:服务器挂载ISO镜像进行安装 1.安装 mkisofs 软件包: #yum install genisoimage 2. ...

  7. 深入解析HTTP请求:了解请求特征与报文格式的关键秘密

    引言 在上一章节中,我们详细探讨了超文本传输协议(HTTP)的基本概念,并且延伸讨论了HTTP请求响应的基本流程.在这个过程中,浏览器首先通过DNS解析来确定要访问的服务器的IP地址,然后与服务器建立 ...

  8. Cplex混合整数规划求解(Python API)

    绝对的原创!罕见的Cplex-Python API混合整数规划求解教程!这是我盯了一天的程序一条条写注释一条条悟出来的•́‸ก 一.问题描述 求解有容量限制的的设施位置问题,使用Benders分解.模 ...

  9. Flask框架——请求扩展、flask中间件、蓝图、分析线程和协程

    文章目录 01 请求扩展 01 before_first_request :项目启动后第一次请求的时候执行 02 before_request:每次请求之前执行 03 after_request:每次 ...

  10. 再学Blazor——扩展方法

    上篇提到 Blazor 组件的高级写法,是采用扩展方法对 HTML 元素和组件进行扩展,以便于书写组件结构和代码阅读.本篇主要介绍扩展方法实现的思路. 什么是扩展方法 要扩展哪个类 扩展方法的实现 1 ...