查看: 251|回复: 0

[Java代码] spring集成okhttp3的步骤详解

发表于 2018-5-4 08:00:02

前言

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文件中增加以下依赖

  1. <dependency>
  2. <groupId>com.squareup.okhttp3</groupId>
  3. <artifactId>okhttp</artifactId>
  4. <version>3.6.0</version>
  5. </dependency>
复制代码

书写配置类

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

  1. @Configuration
  2. public class OkHttpConfiguration {
  3. @Bean
  4. public X509TrustManager x509TrustManager() {
  5. return new X509TrustManager() {
  6. @Override
  7. public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
  8. }
  9. @Override
  10. public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
  11. }
  12. @Override
  13. public X509Certificate[] getAcceptedIssuers() {
  14. return new X509Certificate[0];
  15. }
  16. };
  17. }
  18. @Bean
  19. public SSLSocketFactory sslSocketFactory() {
  20. try {
  21. //信任任何链接
  22. SSLContext sslContext = SSLContext.getInstance("TLS");
  23. sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
  24. return sslContext.getSocketFactory();
  25. } catch (NoSuchAlgorithmException e) {
  26. e.printStackTrace();
  27. } catch (KeyManagementException e) {
  28. e.printStackTrace();
  29. }
  30. return null;
  31. }
  32. /**
  33. * Create a new connection pool with tuning parameters appropriate for a single-user application.
  34. * The tuning parameters in this pool are subject to change in future OkHttp releases. Currently
  35. */
  36. @Bean
  37. public ConnectionPool pool() {
  38. return new ConnectionPool(200, 5, TimeUnit.MINUTES);
  39. }
  40. @Bean
  41. public OkHttpClient okHttpClient() {
  42. return new OkHttpClient.Builder()
  43. .sslSocketFactory(sslSocketFactory(), x509TrustManager())
  44. .retryOnConnectionFailure(false)//是否开启缓存
  45. .connectionPool(pool())//连接池
  46. .connectTimeout(10L, TimeUnit.SECONDS)
  47. .readTimeout(10L, TimeUnit.SECONDS)
  48. .build();
  49. }
  50. }
复制代码

工具类

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

  1. @Component
  2. public class OkHttpUtil {
  3. private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);
  4. @Resource
  5. private OkHttpClient okHttpClient;
  6. /**
  7. * get
  8. *
  9. * @param url 请求的url
  10. * @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
  11. * @return
  12. */
  13. public String get(String url, Map<String, String> queries) {
  14. String responseBody = "";
  15. StringBuffer sb = new StringBuffer(url);
  16. if (queries != null && queries.keySet().size() > 0) {
  17. boolean firstFlag = true;
  18. Iterator iterator = queries.entrySet().iterator();
  19. while (iterator.hasNext()) {
  20. Map.Entry entry = (Map.Entry<String, String>) iterator.next();
  21. if (firstFlag) {
  22. sb.append("?" + entry.getKey() + "=" + entry.getValue());
  23. firstFlag = false;
  24. } else {
  25. sb.append("&" + entry.getKey() + "=" + entry.getValue());
  26. }
  27. }
  28. }
  29. Request request = new Request
  30. .Builder()
  31. .url(sb.toString())
  32. .build();
  33. Response response = null;
  34. try {
  35. response = okHttpClient.newCall(request).execute();
  36. int status = response.code();
  37. if (status == 200) {
  38. return response.body().string();
  39. }
  40. } catch (Exception e) {
  41. logger.error("okhttp put error >> ex = {}", ExceptionUtils.getStackTrace(e));
  42. } finally {
  43. if (response != null) {
  44. response.close();
  45. }
  46. }
  47. return responseBody;
  48. }
  49. /**
  50. * post
  51. *
  52. * @param url 请求的url
  53. * @param params post form 提交的参数
  54. * @return
  55. */
  56. public String post(String url, Map<String, String> params) {
  57. String responseBody = "";
  58. FormBody.Builder builder = new FormBody.Builder();
  59. //添加参数
  60. if (params != null && params.keySet().size() > 0) {
  61. for (String key : params.keySet()) {
  62. builder.add(key, params.get(key));
  63. }
  64. }
  65. Request request = new Request
  66. .Builder()
  67. .url(url)
  68. .post(builder.build())
  69. .build();
  70. Response response = null;
  71. try {
  72. response = okHttpClient.newCall(request).execute();
  73. int status = response.code();
  74. if (status == 200) {
  75. return response.body().string();
  76. }
  77. } catch (Exception e) {
  78. logger.error("okhttp post error >> ex = {}", ExceptionUtils.getStackTrace(e));
  79. } finally {
  80. if (response != null) {
  81. response.close();
  82. }
  83. }
  84. return responseBody;
  85. }
  86. /**
  87. * post 上传文件
  88. *
  89. * @param url
  90. * @param params
  91. * @param fileType
  92. * @return
  93. */
  94. public String postFile(String url, Map<String, Object> params, String fileType) {
  95. String responseBody = "";
  96. MultipartBody.Builder builder = new MultipartBody.Builder();
  97. //添加参数
  98. if (params != null && params.keySet().size() > 0) {
  99. for (String key : params.keySet()) {
  100. if (params.get(key) instanceof File) {
  101. File file = (File) params.get(key);
  102. builder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse(fileType), file));
  103. continue;
  104. }
  105. builder.addFormDataPart(key, params.get(key).toString());
  106. }
  107. }
  108. Request request = new Request
  109. .Builder()
  110. .url(url)
  111. .post(builder.build())
  112. .build();
  113. Response response = null;
  114. try {
  115. response = okHttpClient.newCall(request).execute();
  116. int status = response.code();
  117. if (status == 200) {
  118. return response.body().string();
  119. }
  120. } catch (Exception e) {
  121. logger.error("okhttp postFile error >> ex = {}", ExceptionUtils.getStackTrace(e));
  122. } finally {
  123. if (response != null) {
  124. response.close();
  125. }
  126. }
  127. return responseBody;
  128. }
  129. }
复制代码

使用方法

  1. @Resource
  2. private OkHttpUtil okHttpUtil;
复制代码

总结

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



回复

使用道具 举报