• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

spring集成okhttp3的步骤详解

java 搞代码 4年前 (2022-01-05) 30次浏览 已收录 0个评论

okhttp是一个封装URL,比HttpClient更友好易用的工具,下面这篇文章主要给大家介绍了关于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文件中增加以下依赖

  com.squareup.okhttp3okhttp3.6.0

书写配置类

用@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(); } }

来源gao@daima#com搞(%代@#码@网工具类

自己写的工具类,比较简单,不是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 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) 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 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 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;

总结

以上就是spring集成okhttp3的步骤详解的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:spring集成okhttp3的步骤详解

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址