spring集成okhttp3的步骤详解
前言
okhttp介绍
HTTPisthewaymodernapplicationsnetwork.It'showweexchangedata&media.>DoingHTTPefficientlymakesyourstuffloadfasterandsavesbandwidth.
OkHttpisanHTTPclientthat'sefficientbydefault:
HTTP/2supportallowsallrequeststothesamehosttoshareasocket.
Connectionpoolingreducesrequestlatency(ifHTTP/2isn'tavailable).
TransparentGZIPshrinksdownloadsizes.
Responsecachingavoidsthenetworkcompletelyforrepeatrequests.
OkHttppersevereswhenthenetworkistroublesome:itwillsilentlyrecoverfrom>>commonconnectionproblems.IfyourservicehasmultipleIPaddressesOkHttpwill>attemptalternateaddressesifthefirstconnectfails.ThisisnecessaryforIPv4+IPv6>andforserviceshostedinredundantdatacenters.OkHttpinitiatesnewconnections>withmodernTLSfeatures(SNI,ALPN),andfallsbacktoTLS1.0ifthehandshakefails.UsingOkHttpiseasy.Itsrequest/responseAPIisdesignedwithfluentbuildersandimmutability.Itsupportsbothsynchronousblockingcallsandasynccallswithcallbacks.
OkHttpsupportsAndroid2.3andabove.ForJava,theminimumrequirementis1.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.okhttp3 okhttp 3.6.0
书写配置类
用@Configuration注解该类,等价与XML中配置beans;用@Bean标注方法等价于XML中配置bean。
@Configuration
publicclassOkHttpConfiguration{
@Bean
publicX509TrustManagerx509TrustManager(){
returnnewX509TrustManager(){
@Override
publicvoidcheckClientTrusted(X509Certificate[]x509Certificates,Strings)throwsCertificateException{
}
@Override
publicvoidcheckServerTrusted(X509Certificate[]x509Certificates,Strings)throwsCertificateException{
}
@Override
publicX509Certificate[]getAcceptedIssuers(){
returnnewX509Certificate[0];
}
};
}
@Bean
publicSSLSocketFactorysslSocketFactory(){
try{
//信任任何链接
SSLContextsslContext=SSLContext.getInstance("TLS");
sslContext.init(null,newTrustManager[]{x509TrustManager()},newSecureRandom());
returnsslContext.getSocketFactory();
}catch(NoSuchAlgorithmExceptione){
e.printStackTrace();
}catch(KeyManagementExceptione){
e.printStackTrace();
}
returnnull;
}
/**
*Createanewconnectionpoolwithtuningparametersappropriateforasingle-userapplication.
*ThetuningparametersinthispoolaresubjecttochangeinfutureOkHttpreleases.Currently
*/
@Bean
publicConnectionPoolpool(){
returnnewConnectionPool(200,5,TimeUnit.MINUTES);
}
@Bean
publicOkHttpClientokHttpClient(){
returnnewOkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory(),x509TrustManager())
.retryOnConnectionFailure(false)//是否开启缓存
.connectionPool(pool())//连接池
.connectTimeout(10L,TimeUnit.SECONDS)
.readTimeout(10L,TimeUnit.SECONDS)
.build();
}
}
工具类
自己写的工具类,比较简单,不是REST风格
@Component
publicclassOkHttpUtil{
privatestaticfinalLoggerlogger=LoggerFactory.getLogger(OkHttpUtil.class);
@Resource
privateOkHttpClientokHttpClient;
/**
*get
*
*@paramurl请求的url
*@paramqueries请求的参数,在浏览器?后面的数据,没有可以传null
*@return
*/
publicStringget(Stringurl,Mapqueries){
StringresponseBody="";
StringBuffersb=newStringBuffer(url);
if(queries!=null&&queries.keySet().size()>0){
booleanfirstFlag=true;
Iteratoriterator=queries.entrySet().iterator();
while(iterator.hasNext()){
Map.Entryentry=(Map.Entry)iterator.next();
if(firstFlag){
sb.append("?"+entry.getKey()+"="+entry.getValue());
firstFlag=false;
}else{
sb.append("&"+entry.getKey()+"="+entry.getValue());
}
}
}
Requestrequest=newRequest
.Builder()
.url(sb.toString())
.build();
Responseresponse=null;
try{
response=okHttpClient.newCall(request).execute();
intstatus=response.code();
if(status==200){
returnresponse.body().string();
}
}catch(Exceptione){
logger.error("okhttpputerror>>ex={}",ExceptionUtils.getStackTrace(e));
}finally{
if(response!=null){
response.close();
}
}
returnresponseBody;
}
/**
*post
*
*@paramurl请求的url
*@paramparamspostform提交的参数
*@return
*/
publicStringpost(Stringurl,Mapparams){
StringresponseBody="";
FormBody.Builderbuilder=newFormBody.Builder();
//添加参数
if(params!=null&¶ms.keySet().size()>0){
for(Stringkey:params.keySet()){
builder.add(key,params.get(key));
}
}
Requestrequest=newRequest
.Builder()
.url(url)
.post(builder.build())
.build();
Responseresponse=null;
try{
response=okHttpClient.newCall(request).execute();
intstatus=response.code();
if(status==200){
returnresponse.body().string();
}
}catch(Exceptione){
logger.error("okhttpposterror>>ex={}",ExceptionUtils.getStackTrace(e));
}finally{
if(response!=null){
response.close();
}
}
returnresponseBody;
}
/**
*post上传文件
*
*@paramurl
*@paramparams
*@paramfileType
*@return
*/
publicStringpostFile(Stringurl,Mapparams,StringfileType){
StringresponseBody="";
MultipartBody.Builderbuilder=newMultipartBody.Builder();
//添加参数
if(params!=null&¶ms.keySet().size()>0){
for(Stringkey:params.keySet()){
if(params.get(key)instanceofFile){
Filefile=(File)params.get(key);
builder.addFormDataPart(key,file.getName(),RequestBody.create(MediaType.parse(fileType),file));
continue;
}
builder.addFormDataPart(key,params.get(key).toString());
}
}
Requestrequest=newRequest
.Builder()
.url(url)
.post(builder.build())
.build();
Responseresponse=null;
try{
response=okHttpClient.newCall(request).execute();
intstatus=response.code();
if(status==200){
returnresponse.body().string();
}
}catch(Exceptione){
logger.error("okhttppostFileerror>>ex={}",ExceptionUtils.getStackTrace(e));
}finally{
if(response!=null){
response.close();
}
}
returnresponseBody;
}
}
使用方法
@Resource privateOkHttpUtilokHttpUtil;
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。