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/
特點(diǎn)
1.支持http和https協(xié)議,api相同,易用;
2.http使用線程池,https使用多路復(fù)用;
3.okhttp支持同步和異步調(diào)用;
4.支持普通form和文件上傳form;
5.提供了攔截器,操作請求和響應(yīng)(日志,請求頭,body等);
6.okhttp可以設(shè)置緩存;
準(zhǔn)備工作
在pom.xml文件中增加以下依賴
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.6.0</version> </dependency>
書寫配置類
用@Configuration注解該類,等價(jià)與XML中配置beans;用@Bean標(biāo)注方法等價(jià)于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風(fēng)格
@Component
public class OkHttpUtil {
private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);
@Resource
private OkHttpClient okHttpClient;
/**
* get
*
* @param url 請求的url
* @param queries 請求的參數(shù),在瀏覽器?后面的數(shù)據(jù),沒有可以傳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 提交的參數(shù)
* @return
*/
public String post(String url, Map<String, String> params) {
String responseBody = "";
FormBody.Builder builder = new FormBody.Builder();
//添加參數(shù)
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();
//添加參數(shù)
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;
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
SpringBoot通過Filter實(shí)現(xiàn)整個(gè)項(xiàng)目接口的SQL注入攔截詳解
這篇文章主要介紹了SpringBoot通過Filter實(shí)現(xiàn)整個(gè)項(xiàng)目接口的SQL注入攔截詳解,SQL注入是比較常見的網(wǎng)絡(luò)攻擊方式之一,在客戶端在向服務(wù)器發(fā)送請求的時(shí)候,sql命令通過表單提交或者url字符串拼接傳遞到后臺(tái)持久層,最終達(dá)到欺騙服務(wù)器執(zhí)行惡意的SQL命令,需要的朋友可以參考下2023-12-12
超簡潔java實(shí)現(xiàn)雙色球若干注隨機(jī)號(hào)碼生成(實(shí)例代碼)
這篇文章主要介紹了超簡潔java實(shí)現(xiàn)雙色球若干注隨機(jī)號(hào)碼生成(實(shí)例代碼),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04
java實(shí)現(xiàn)基于UDP協(xié)議網(wǎng)絡(luò)Socket編程(C/S通信)
這篇文章主要介紹了java實(shí)現(xiàn)基于UDP協(xié)議網(wǎng)絡(luò)Socket編程(C/S通信),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
spring @Cacheable擴(kuò)展實(shí)現(xiàn)緩存自動(dòng)過期時(shí)間及自動(dòng)刷新功能
用過spring cache的朋友應(yīng)該會(huì)知道,Spring Cache默認(rèn)是不支持在@Cacheable上添加過期時(shí)間的,雖然可以通過配置緩存容器時(shí)統(tǒng)一指定,本文主要介紹了如何基于spring @Cacheable擴(kuò)展實(shí)現(xiàn)緩存自動(dòng)過期時(shí)間以及緩存即將到期自動(dòng)刷新,2024-02-02
spring profile 多環(huán)境配置管理詳解
這篇文章主要介紹了 spring profile 多環(huán)境配置管理詳解的相關(guān)資料,需要的朋友可以參考下2017-01-01
springboot?使用clickhouse實(shí)時(shí)大數(shù)據(jù)分析引擎(使用方式)
這篇文章主要介紹了springboot?使用clickhouse實(shí)時(shí)大數(shù)據(jù)分析引擎的方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2022-02-02
java之使用多線程代替for循環(huán)(解決主線程提前結(jié)束問題)
這篇文章主要介紹了java之使用多線程代替for循環(huán)(解決主線程提前結(jié)束問題),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
解決spring cloud gateway 獲取body內(nèi)容并修改的問題
這篇文章主要介紹了解決spring cloud gateway 獲取body內(nèi)容并修改的問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12

