spring集成okhttp3的步骤详解

前言

okhttp 介绍

HTTP is the way modern applications network. It's how we exchange data & media. >Doing HTTP efficiently makes your stuff load faster and saves bandwidth.

OkHttp is an HTTP client that's efficient by default:

HTTP/2 support allows all requests to the same host to share a socket.
Connection pooling reduces request latency (if HTTP/2 isn't available).
Transparent GZIP shrinks download sizes.
Response caching avoids the network completely for repeat requests.
OkHttp perseveres when the network is troublesome: it will silently recover from > >common connection problems. If your service has multiple IP addresses OkHttp will >attempt alternate addresses if the first connect fails. This is necessary for IPv4+IPv6 >and for services hosted in redundant data centers. OkHttp initiates new connections >with modern TLS features (SNI, ALPN), and falls back to TLS 1.0 if the handshake fails.

Using OkHttp is easy. Its request/response API is designed with fluent builders and immutability. It supports both synchronous blocking calls and async calls with callbacks.

OkHttp supports Android 2.3 and above. For Java, the minimum requirement is 1.7. —摘自 https://square.github.io/okhttp/

特点

1.支持http和https协议,api相同,易用;

2.http使用线程池,https使用多路复用;

3.okhttp支持同步和异步调用;

4.支持普通form和文件上传form;

5.提供了拦截器,操作请求和响应(日志,请求头,body等);

6.okhttp可以设置缓存;

准备工作

在pom.xml文件中增加以下依赖

<dependency>
 <groupId>com.squareup.okhttp3</groupId>
 <artifactId>okhttp</artifactId>
 <version>3.6.0</version>
</dependency>

书写配置类

用@Configuration注解该类,等价与XML中配置beans;用@Bean标注方法等价于XML中配置bean。

@Configuration
public class OkHttpConfiguration {
 @Bean
 public X509TrustManager x509TrustManager() {
 return new X509TrustManager() {
  @Override
  public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
  }
  @Override
  public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
  }
  @Override
  public X509Certificate[] getAcceptedIssuers() {
  return new X509Certificate[0];
  }
 };
 }
 @Bean
 public SSLSocketFactory sslSocketFactory() {
 try {
  //信任任何链接
  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
  return sslContext.getSocketFactory();
 } catch (NoSuchAlgorithmException e) {
  e.printStackTrace();
 } catch (KeyManagementException e) {
  e.printStackTrace();
 }
 return null;
 }
 /**
 * Create a new connection pool with tuning parameters appropriate for a single-user application.
 * The tuning parameters in this pool are subject to change in future OkHttp releases. Currently
 */
 @Bean
 public ConnectionPool pool() {
 return new ConnectionPool(200, 5, TimeUnit.MINUTES);
 }
 @Bean
 public OkHttpClient okHttpClient() {
 return new OkHttpClient.Builder()
  .sslSocketFactory(sslSocketFactory(), x509TrustManager())
  .retryOnConnectionFailure(false)//是否开启缓存
  .connectionPool(pool())//连接池
  .connectTimeout(10L, TimeUnit.SECONDS)
  .readTimeout(10L, TimeUnit.SECONDS)
  .build();
 }
}

工具类

自己写的工具类,比较简单,不是REST风格

@Component
public class OkHttpUtil {
 private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);
 @Resource
 private OkHttpClient okHttpClient;
 /**
 * get
 *
 * @param url 请求的url
 * @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
 * @return
 */
 public String get(String url, Map<String, String> queries) {
 String responseBody = "";
 StringBuffer sb = new StringBuffer(url);
 if (queries != null && queries.keySet().size() > 0) {
  boolean firstFlag = true;
  Iterator iterator = queries.entrySet().iterator();
  while (iterator.hasNext()) {
  Map.Entry entry = (Map.Entry<String, String>) iterator.next();
  if (firstFlag) {
   sb.append("?" + entry.getKey() + "=" + entry.getValue());
   firstFlag = false;
  } else {
   sb.append("&" + entry.getKey() + "=" + entry.getValue());
  }
  }
 }
 Request request = new Request
  .Builder()
  .url(sb.toString())
  .build();
 Response response = null;
 try {
  response = okHttpClient.newCall(request).execute();
  int status = response.code();
  if (status == 200) {
  return response.body().string();
  }
 } catch (Exception e) {
  logger.error("okhttp put error >> ex = {}", ExceptionUtils.getStackTrace(e));
 } finally {
  if (response != null) {
  response.close();
  }
 }
 return responseBody;
 }
 /**
 * post
 *
 * @param url 请求的url
 * @param params post form 提交的参数
 * @return
 */
 public String post(String url, Map<String, String> params) {
 String responseBody = "";
 FormBody.Builder builder = new FormBody.Builder();
 //添加参数
 if (params != null && params.keySet().size() > 0) {
  for (String key : params.keySet()) {
  builder.add(key, params.get(key));
  }
 }
 Request request = new Request
  .Builder()
  .url(url)
  .post(builder.build())
  .build();
 Response response = null;
 try {
  response = okHttpClient.newCall(request).execute();
  int status = response.code();
  if (status == 200) {
  return response.body().string();
  }
 } catch (Exception e) {
  logger.error("okhttp post error >> ex = {}", ExceptionUtils.getStackTrace(e));
 } finally {
  if (response != null) {
  response.close();
  }
 }
 return responseBody;
 }
 /**
 * post 上传文件
 *
 * @param url
 * @param params
 * @param fileType
 * @return
 */
 public String postFile(String url, Map<String, Object> params, String fileType) {
 String responseBody = "";
 MultipartBody.Builder builder = new MultipartBody.Builder();
 //添加参数
 if (params != null && params.keySet().size() > 0) {
  for (String key : params.keySet()) {
  if (params.get(key) instanceof File) {
   File file = (File) params.get(key);
   builder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse(fileType), file));
   continue;
  }
  builder.addFormDataPart(key, params.get(key).toString());
  }
 }
 Request request = new Request
  .Builder()
  .url(url)
  .post(builder.build())
  .build();
 Response response = null;
 try {
  response = okHttpClient.newCall(request).execute();
  int status = response.code();
  if (status == 200) {
  return response.body().string();
  }
 } catch (Exception e) {
  logger.error("okhttp postFile error >> ex = {}", ExceptionUtils.getStackTrace(e));
 } finally {
  if (response != null) {
  response.close();
  }
 }
 return responseBody;
 }
}

使用方法

@Resource
private OkHttpUtil okHttpUtil;

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对我们的支持。

(0)

相关推荐

  • spring集成okhttp3的步骤详解

    前言 okhttp 介绍 HTTP is the way modern applications network. It's how we exchange data & media. >Doing HTTP efficiently makes your stuff load faster and saves bandwidth. OkHttp is an HTTP client that's efficient by default: HTTP/2 support allows all r

  • springboot 集成dubbo的步骤详解

    目录 第一步 搭建zookeeper环境 第二步 springboot集成dubbo 1.项目目录机构 2.代码编写 2.1 api目录 2.2 consumer目录 web访问.接口调用以及dubbo配置编写 2.3 provider目录 api接口实现以及dubbo配置 第三步 测试dubbo远程服务调用 附录: 写在前面:在阅读本文前,请前拥有dubbo基础知识,springboot知识 dubbo官网: http://dubbo.apache.orgdubbo github 源码地址:h

  • shiro与spring集成基础Hello案例详解

    这篇文章主要介绍了shiro与spring集成基础Hello案例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 shiro的四大基石 身份验证(登录)Authentication:身份认证 / 登录,验证用户是不是拥有相应的身份: 授权(权限)Authorization:验证某个已登录的用户是否拥有某个权限 密码学(密码加密) Cryptography:加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储: 会话管理 Sessio

  • spring 集成 mybatis的实例详解

    环境配置 1>先创建maven的quickstart项目;并且创建dao层,service层,controller层,po层,mapper,resources以及下面的配置文件(db.properties,log4j.properties,mybatis.xml,spring.xml). 2>配置pom.xml ​ 修改jdk版本; ​ 添加依赖: ​ junit版本改为4.12;spring-context;spring-test;spring-jdbc;spring-tx(事务);aspe

  • Spring Boot支持HTTPS步骤详解

    Spring Boot中启动HTTPS 如果你使用Spring Boot,并且想在内嵌tomcat中添加HTTPS,需要有一个证书. 两种方式 自己通过keytool生成 通过证书授权机构购买 这里采用第一种方式,采用keytool生成. -genkey 生成秘钥 -alias 别名 -keyalg 秘钥算法 -keysize 秘钥长度 -validity 有效期 -keystore 生成秘钥库的存储路径和名称 -keypass 秘钥口令 -storepass 秘钥库口令 -dname 拥有者信

  • Springboot集成Spring Security实现JWT认证的步骤详解

    1 简介 Spring Security作为成熟且强大的安全框架,得到许多大厂的青睐.而作为前后端分离的SSO方案,JWT也在许多项目中应用.本文将介绍如何通过Spring Security实现JWT认证. 用户与服务器交互大概如下: 客户端获取JWT,一般通过POST方法把用户名/密码传给server: 服务端接收到客户端的请求后,会检验用户名/密码是否正确,如果正确则生成JWT并返回:不正确则返回错误: 客户端拿到JWT后,在有效期内都可以通过JWT来访问资源了,一般把JWT放在请求头:一次

  • 在Spring Boot应用程序中使用Apache Kafka的方法步骤详解

    第1步:生成我们的项目: Spring Initializr来生成我们的项目.我们的项目将提供Spring MVC / Web支持和Apache Kafka支持. 第2步:发布/读取Kafka主题中的消息: <b>public</b> <b>class</b> User { <b>private</b> String name; <b>private</b> <b>int</b> age

  • Spring Boot整合EhCache的步骤详解

    本文讲解Spring Boot与EhCache的整合. 1 EhCache简介 EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认CacheProvider.Ehcache是一种广泛使用的开源Java分布式缓存.主要面向通用缓存,Java EE和轻量级容器.它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点. 2 Spring Boot整合EhCache步骤 2.

  • Spring Cloud中使用jib进行docker部署的步骤详解

    Jib介绍 Jib 是 Google 开发的可以直接构建 Java 应用的 Docker 和 OCI 镜像的类库,以 Maven 和 Gradle 插件形式提供. 通过 Jib,Java 开发者可以使用他们熟悉的 Java 工具来构建容器.Jib 是一个快速而简单的容器镜像构建工具,它负责处理将应用程序打包到容器镜像中所需的所有步骤.它不需要你编写 Dockerfile 或安装 Docker,而且可以直接集成到 Maven 和 Gradle中 -- 只需要将插件添加到构建中,就可以立即将 Jav

  • 基于spring boot 1.5.4 集成 jpa+hibernate+jdbcTemplate(详解)

    1.pom添加依赖 <!-- spring data jpa,会注入tomcat jdbc pool/hibernate等 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <

随机推荐