当前位置: 移动技术网 > IT编程>开发语言>Java > spring集成okhttp3的步骤详解

spring集成okhttp3的步骤详解

2019年07月19日  | 移动技术网IT编程  | 我要评论

大学生网,刘心武揭秘红楼梦下载,少年特工科迪国语

前言

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

<dependency>
 <groupid>com.squareup.okhttp3</groupid>
 <artifactid>okhttp</artifactid>
 <version>3.6.0</version>
</dependency>

书写配置类

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

工具类

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

使用方法

@resource
private okhttputil okhttputil;

总结

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网