iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >怎么使用HttpClient和OkHttp
  • 445
分享到

怎么使用HttpClient和OkHttp

2023-06-16 14:06:15 445人浏览 八月长安
摘要

这篇文章主要讲解了“怎么使用HttpClient和OkHttp”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么使用HttpClient和OkHttp”吧!使用HttpClient和OkHt

这篇文章主要讲解了“怎么使用HttpClient和OkHttp”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么使用HttpClient和OkHttp”吧!

使用

HttpClient和OkHttp一般用于调用其它服务,一般服务暴露出来的接口都为http,http常用请求类型就为GET、PUT、POST和DELETE,因此主要介绍这些请求类型的调用

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("h3t").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("h3t2").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("h3t").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方法进行取消 测试结果:

task canceled  cost 9110 msc  java.net.SocketException: socket closed...【省略】

小结

OkHttp使用build模式创建对象来的更简洁一些,并且使用.post/.delete/.put/.get方法表示请求类型,不需要像HttpClient创建HttpGet、HttpPost等这些方法来创建请求类型

依赖包上,如果HttpClient需要发送异步请求、实现文件上传,需要额外的引入异步请求依赖

<!---文件上传-->   <dependency>       <groupId>org.apache.httpcomponents</groupId>       <artifactId>httpmime</artifactId>       <version>4.5.3</version>   </dependency>   <!--异步请求-->   <dependency>       <groupId>org.apache.httpcomponents</groupId>       <artifactId>httpasyncclient</artifactId>       <version>4.5.3</version>   </dependency>

请求的取消,HttpClient使用abort方法,OkHttp使用cancel方法,都挺简单的,如果使用的是异步client,则在抛出异常时调用取消请求的方法即可

超时设置

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一旦设置了超时时间,所有请求类型的超时时间也就确定

HttpClient和OkHttp性能比较

测试环境:

每种测试用例都测试五次,排除偶然性

client连接为单例:

怎么使用HttpClient和OkHttp

client连接不为单例:

怎么使用HttpClient和OkHttp

单例模式下,HttpClient的响应速度要更快一些,单位为毫秒,性能差异相差不大

非单例模式下,OkHttp的性能更好,HttpClient创建连接比较耗时,因为多数情况下这些资源都会写成单例模式,因此图一的测试结果更具有参考价值

感谢各位的阅读,以上就是“怎么使用HttpClient和OkHttp”的内容了,经过本文的学习后,相信大家对怎么使用HttpClient和OkHttp这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!

--结束END--

本文标题: 怎么使用HttpClient和OkHttp

本文链接: https://www.lsjlt.com/news/283864.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 怎么使用HttpClient和OkHttp
    这篇文章主要讲解了“怎么使用HttpClient和OkHttp”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么使用HttpClient和OkHttp”吧!使用HttpClient和OkHt...
    99+
    2023-06-16
  • Feign 使用HttpClient和OkHttp方式
    目录使用HttpClient和OkHttp使用HttpClient使用OkHttpOpenFeign替换为OkHttppom中引入feign-okhttp在application.y...
    99+
    2024-04-02
  • 浅谈HttpClient、okhttp和RestTemplate的区别
    一、HttpClient 1、pom依赖 <!--HttpClient--> <dependency> <groupId>common...
    99+
    2024-04-02
  • 基于springboot的RestTemplate、okhttp和HttpClient对比分析
    1、HttpClient:代码复杂,还得操心资源回收等。代码很复杂,冗余代码多,不建议直接使用。 2、RestTemplate: 是 Spring 提供的用于访问Rest服务的客户端...
    99+
    2024-04-02
  • Java HttpClient怎么使用
    今天小编给大家分享一下Java HttpClient怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。1、导入...
    99+
    2023-07-02
  • Android中OKHttp怎么使用
    OKHttp是一个开源的HTTP客户端库,用于在Android中发送和接收网络请求。下面是一个示例,展示了如何在Android中使用...
    99+
    2023-09-13
    Android
  • Java原生HttpClient怎么使用
    这篇文章主要介绍“Java原生HttpClient怎么使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Java原生HttpClient怎么使用”文章能帮助大家解决问题。1.信任证书管理类packa...
    99+
    2023-06-29
  • android的httpClient怎么使用
    在Android中,可以使用HttpClient来发送HTTP请求。以下是使用HttpClient的基本步骤:1. 导入HttpCl...
    99+
    2023-08-23
    android httpClient
  • Java中的OkHttp怎么使用
    今天小编给大家分享一下Java中的OkHttp怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。什么是OKHttp一般在...
    99+
    2023-06-30
  • java怎么使用HttpClient调用接口
    这篇文章主要介绍“java怎么使用HttpClient调用接口”,在日常操作中,相信很多人在java怎么使用HttpClient调用接口问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”java怎么使用HttpC...
    99+
    2023-07-04
  • Android OKhttp使用(下载和上传文件)
    Android okhttp的使用 首先在build.gradle中引入okhttp implementation 'com.squareup.okhttp3:okhttp:3.14.2' implementation 'co...
    99+
    2023-08-23
    okhttp android
  • Java服务RestTemplate与HttpClient怎么使用
    本篇内容主要讲解“Java服务RestTemplate与HttpClient怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Java服务RestTemplate与HttpClient怎么使...
    99+
    2023-07-06
  • Android-Okhttp的使用解析
    okhttp是Android6.0推出的网络框架。由于谷歌在Android6.0的之后,将HttpClient相关属性取消掉,导致Volley框架不能正常使用。所以才有了今天的Okhttp。 Okhttp进行网络访问通常有两种方式...
    99+
    2023-05-31
    android okhttp roi
  • java中怎么使用httpclient提交表单
    在Java中使用HttpClient提交表单可以通过以下步骤实现:1. 添加依赖:首先,需要在项目中添加HttpClient的依赖。...
    99+
    2023-08-08
    java httpclient
  • Android OKHttp使用简介
    目录配置 创建OkHttpClient 同步get请求异步get请求 同步post请求异步post请求上传文件表单提交下面是官网给出的OKHTTP的特点: 支持HTTP/2...
    99+
    2024-04-02
  • HttpClient jar包使用详解
    HttpClient是一个开源的HTTP客户端工具包,用来进行HTTP通信。它可以用来发送HTTP请求和接收HTTP响应,支持HTT...
    99+
    2023-09-15
    HttpClient
  • 怎么在Spring中远程调用HttpClient和RestTemplate
    这篇文章将为大家详细讲解有关怎么在Spring中远程调用HttpClient和RestTemplate,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。一、HttpClient导入坐标<d...
    99+
    2023-06-07
  • C#如何使用HttpClient
    这篇文章给大家分享的是有关C#如何使用HttpClient的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。错误使用New HttpClient如下面一段代码,日常开发中经常使用的 call http 方式,每次 n...
    99+
    2023-06-25
  • ASP.NETCore使用HttpClient调用WebService
    一、创建WebService 我们使用VS创建一个WebService,增加一个PostTest方法,方法代码如下 using System.Web.Services; names...
    99+
    2024-04-02
  • .NET HttpClient简单使用教程
    创建一个名为HttpClientTest的Web API项目 新建Clients文件夹,用于存放自定义的HttpClient 在Clients下新建一个MyHttpClient类...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作