一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - spring集成okhttp3的步驟詳解

spring集成okhttp3的步驟詳解

2021-04-22 13:22斜陽 Java教程

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

?
1
2
3
4
5
<dependency>
 <groupid>com.squareup.okhttp3</groupid>
 <artifactid>okhttp</artifactid>
 <version>3.6.0</version>
</dependency>

書寫配置類

用@configuration注解該類,等價與xml中配置beans;用@bean標注方法等價于xml中配置bean。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
@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風格

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
@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;
 }
}

使用方法

?
1
2
@resource
private okhttputil okhttputil;

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。

原文鏈接:https://miaoxinwei.github.io/2017/04/21/spring-集成-okhttp3/

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 洗濯屋H纯肉动漫在线观看 武侠艳妇屈辱的张开双腿 午夜在线观看免费观看 视频 | 国产一级片视频 | 天堂网在线网站成人午夜网站 | 欧美日韩一区二区三区免费不卡 | 国产农村一级特黄α真人毛片 | 久久精品麻豆国产天美传媒果冻 | 九九艹| 国产嫩草视频 | 亚洲第一色网 | 小柔的性放荡羞辱日记 | 欧美日韩亚洲区久久综合 | 亚洲天堂2015 | 午夜福利理论片在线播放 | 亚洲高清在线天堂精品 | aaa一级特黄 | 午夜爱爱爱爱爽爽爽视频网站 | 亚洲国产综合精品 | 无码一区国产欧美在线资源 | 2022国产在线观看 | 国内精品久久久久香蕉 | 日本狠狠操 | 青青视频国产依人在线 | 色综合天天综合网看在线影院 | 成人国产精品一区二区不卡 | 天堂一区二区在线观看 | 日本精品久久久久久久久免费 | 亚洲精品一区二区三区中文字幕 | 欧美日韩国产一区二区三区伦 | 亚州精品视频 | 国产午夜免费秋霞影院 | www.99热.com| 日本在线视频免费看 | 91短视频版高清在线观看免费 | 成人免费国产欧美日韩你懂的 | 欧美一区二区三区高清不卡tv | 天堂网在线.www天堂在线视频 | 91精品国产高清久久久久久 | 女王脚奴vk| 啊啊啊好大视频 | 日本不卡不码高清免费观看 | 十大看黄网站 |