当前位置: 移动技术网 > IT编程>移动开发>Android > 浅谈Android开发系列网络篇之Retrofit

浅谈Android开发系列网络篇之Retrofit

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

玛丽莎官网,嫩雀儿,搞笑贴吧

retrofit是一个不错的网络请求库,用官方自己的介绍就是:

a type-safe rest client for android and java

看官网的介绍用起来很省事,不过如果不了解它是怎么实现的也不太敢用,不然出问题了就不知道怎么办了。这几天比较闲就下下来看了一下,了解一下大概实现方法,细节就不追究了。先来看一个官网的例子,详细说明去看

简单示例

首先定义请求接口,即程序中都需要什么请求操作

public interface githubservice {
 @get("/users/{user}/repos")
 list<repo> listrepos(@path("user") string user);
}

然后通过restadapter生成一个刚才定义的接口的实现类,使用的是动态代理。

restadapter restadapter = new restadapter.builder()
  .setendpoint("https://api.github.com")
  .build();

githubservice service = restadapter.create(githubservice.class);

现在就可以调用接口进行请求了

list<repo> repos = service.listrepos("octocat");

使用就是这么简单,请求时直接调用接口就行了,甚至不用封装参数,因为参数的信息已经在定义接口时通过annotation定义好了。

从上面的例子可以看到接口直接返回了需要的java类型,而不是byte[]或string,解析数据的地方就是converter,这个是可以自定义的,默认是用gson解析,也就是说默认认为服务器返回的是json数据,可以通过指定不同的convert使用不同的解析方法,如用jackson解析json,或自定义xmlconvert解析xml数据。

retrofit的使用就是以下几步:

1.定义接口,参数声明,url都通过annotation指定

2.通过restadapter生成一个接口的实现类(动态代理)

3.调用接口请求数据

接口的定义要用用rtrofit定义的一些annotation,所以先看一下annotation的。

annotation

以上面的示例中的接口来看

@get("/group/{id}/users")
list<user> grouplist(@path("id") int groupid);

先看@get

/** make a get request to a rest path relative to base url. */
@documented
@target(method)
@retention(runtime)
@restmethod("get")
public @interface get {
 string value();
}

@get本身也被几个anotation注解,@target表示@get注解是用于方法的,value方法就返回这个注解的value值,在上例中就是/group/{id}/users,然后就是@restmethod

@documented
@target(annotation_type)
@retention(runtime)
public @interface restmethod {
 string value();
 boolean hasbody() default false;
}

restmethod是一个用于annotation的annotation,比如上面的例子中用来注解的@get,value方法就返回get,hasbody表示是否有body,对于post这个方法就返回true

@documented
@target(method)
@retention(runtime)
@restmethod(value = "post", hasbody = true)
public @interface post {
 string value();
}

retrofit的annotation包含请求方法相关的@get、@post、@head、@put、@deleta、@patch,和参数相关的@path、@field、@multipart等。

定义了annotation要就有解析它的方法,在retrofit中解析的位置就是restmethodinfo,但在这之前需要先看哪里使用了restmethodinfo,前面说了retrofit使用了动态代理生成了我们定义的接口的实现类,而这个实现类是通过restadapter.create返回的,所以使用动态代理的位置就是restadapter,接下来就看一下restadapter。

restadapter

restadapter restadapter = new restadapter.builder()
  .setendpoint("https://api.github.com")
  .build();

githubservice service = restadapter.create(githubservice.class);

public restadapter build() {
 if (endpoint == null) {
  throw new illegalargumentexception("endpoint may not be null.");
 }
 
 ensuresanedefaults();
 
 return new restadapter(endpoint, clientprovider, httpexecutor, callbackexecutor,
   requestinterceptor, converter, profiler, errorhandler, log, loglevel);
}

setendpoint就不说了,接口中定义的都是相对url,endpoint就是域名,build方法调用ensuresanedefaults()方法,然后就构造了一个restadapter对象,构造函数的参数中传入了endpoint外的几个对象,这几个对象就是在ensuresanedefaults()中初始化的。

private void ensuresanedefaults() {
 if (converter == null) { converter = platform.get().defaultconverter(); }
 if (clientprovider == null) { clientprovider = platform.get().defaultclient(); }
 if (httpexecutor == null) { httpexecutor = platform.get().defaulthttpexecutor(); }
 if (callbackexecutor == null) { callbackexecutor = platform.get().defaultcallbackexecutor(); }
 if (errorhandler == null) { errorhandler = errorhandler.default; }
 if (log == null) { log = platform.get().defaultlog(); }
 if (requestinterceptor == null) { requestinterceptor = requestinterceptor.none; }
}

ensuresanedefaults()中初始化了很多成员,errorhandler、log就不看了,其他的除了requestinterceptor都是通过platform对象获得的,所以要先看下platform

platform

private static final platform platform = findplatform();
 static final boolean has_rx_java = hasrxjavaonclasspath();

 static platform get() {
  return platform;
 }

 private static platform findplatform() {
  try {
   class.forname("android.os.build");
   if (build.version.sdk_int != 0) {
    return new android();
   }
  } catch (classnotfoundexception ignored) {
  }

  if (system.getproperty("com.google.appengine.runtime.version") != null) {
   return new appengine();
  }

  return new base();
 }

使用了单例的platform,通过findplatform()初始化实例,如果是android平台就使用platform.android,如果是google appengine就使用platform.appengine,否则使用platform.base,这些都是platform的子类,其中appengine又是base的子类。

platform是一个抽象类,定义了以下几个抽象方法,这几个方法的作用就是返回一些restadapter中需要要用到成员的默认实现

abstract converter defaultconverter(); // 默认的converter,用于将请求结果转化成需要的数据,如gsonconverter将json请求结果用gson解析成java对象
 abstract client.provider defaultclient(); // http请求类,如果是appengine就使用`urlfetchclient`,否则如果有okhttp就使用okhttp,如果是android,2.3以后使用httpurlconnection,2.3以前使用httpclient
 abstract executor defaulthttpexecutor(); // 用于执行http请求的executor
 abstract executor defaultcallbackexecutor(); // callback调用中用于执行callback的executor(可能是同步的)
 abstract restadapter.log defaultlog(); // log接口,用于输出log

看完platform的接口再看ensuresanedefaults就清楚了,初始化转化数据的converter、执行请求的client、执行请求的executor、执行callback的executor、log输出类、错误处理类和用于在请求前添加额外处理的拦截请求的interceptor。

converter默认都是用的gsonconverter,就不看了,defaultclient返回执行网络请求的client

platform.android

@override client.provider defaultclient() {
 final client client;
 if (hasokhttponclasspath()) {
  client = okclientinstantiator.instantiate();
 } else if (build.version.sdk_int < build.version_codes.gingerbread) {
  client = new androidapacheclient();
 } else {
  client = new urlconnectionclient();
 }
 return new client.provider() {
  @override public client get() {
   return client;
  }
 };
}

platform.base

@override client.provider defaultclient() {
 final client client;
 if (hasokhttponclasspath()) {
  client = okclientinstantiator.instantiate();
 } else {
  client = new urlconnectionclient();
 }
 return new client.provider() {
  @override public client get() {
   return client;
  }
 };
}

platform.appengine

@override client.provider defaultclient() {
 final urlfetchclient client = new urlfetchclient();
 return new client.provider() {
  @override public client get() {
   return client;
  }
 };
}

对于android,优先使用okhttp,否则2.3以后使用httpurlconnection,2.3以前使用httpclient

defaulthttpexecutor就是返回一个executor,执行请求的线程在这个executor中执行,就做了一件事,把线程设置为后台线程

defaultcallbackexecutor用于执行callback类型的请求时,提供一个executor执行callback的runnable

platform.base

@override executor defaultcallbackexecutor() {
  return new utils.synchronousexecutor();
}

platform.android

@override executor defaultcallbackexecutor() {
  return new mainthreadexecutor();
}

synchronousexecutor

static class synchronousexecutor implements executor {
  @override public void execute(runnable runnable) {
   runnable.run();
  }
}

mainthreadexecutor

public final class mainthreadexecutor implements executor {
 private final handler handler = new handler(looper.getmainlooper());

 @override public void execute(runnable r) {
  handler.post(r);
 }
}

如果是android,通过handler将回调发送到主线程执行,如果非android,直接同步执行。

platform看完了,restadapter的成员初始化完成,就要看怎么通过restadapter.create生成我们定义的接口的实现类了

restadapter.create

 public <t> t create(class<t> service) {
  utils.validateserviceclass(service);
  return (t) proxy.newproxyinstance(service.getclassloader(), new class<?>[] { service },
    new resthandler(getmethodinfocache(service)));
 }
 
 map<method, restmethodinfo> getmethodinfocache(class<?> service) {
  synchronized (servicemethodinfocache) {
   map<method, restmethodinfo> methodinfocache = servicemethodinfocache.get(service);
   if (methodinfocache == null) {
    methodinfocache = new linkedhashmap<method, restmethodinfo>();
    servicemethodinfocache.put(service, methodinfocache);
   }
   return methodinfocache;
  }
 }

使用了动态代理,invocationhandler是resthandler,resthandler有一个参数,是method->restmethodinfo的映射,初始化时这个映射是空的。重点就是这两个了:resthandler,restmethodinfo,

@override public object invoke(object proxy, method method, final object[] args)
  throws throwable {
 // if the method is a method from object then defer to normal invocation.
 if (method.getdeclaringclass() == object.class) { // 1
  return method.invoke(this, args);
 }
 
 // load or create the details cache for the current method.
 final restmethodinfo methodinfo = getmethodinfo(methoddetailscache, method); // 2
 
 if (methodinfo.issynchronous) { // 3
  try {
   return invokerequest(requestinterceptor, methodinfo, args);
  } catch (retrofiterror error) {
   throwable newerror = errorhandler.handleerror(error);
   if (newerror == null) {
    throw new illegalstateexception("error handler returned null for wrapped exception.",
      error);
   }
   throw newerror;
  }
 }
 
 if (httpexecutor == null || callbackexecutor == null) {
  throw new illegalstateexception("asynchronous invocation requires calling setexecutors.");
 }
 
 // apply the interceptor synchronously, recording the interception so we can replay it later.
 // this way we still defer argument serialization to the background thread.
 final requestinterceptortape interceptortape = new requestinterceptortape();
 requestinterceptor.intercept(interceptortape); // 4
 
 if (methodinfo.isobservable) { // 5
  if (rxsupport == null) {
   if (platform.has_rx_java) {
    rxsupport = new rxsupport(httpexecutor, errorhandler);
   } else {
    throw new illegalstateexception("observable method found but no rxjava on classpath");
   }
  }
  
  return rxsupport.createrequestobservable(new callable<responsewrapper>() {
   @override public responsewrapper call() throws exception {
    return (responsewrapper) invokerequest(interceptortape, methodinfo, args);
   }
  });
 }
 
 callback<?> callback = (callback<?>) args[args.length - 1]; // 6
 httpexecutor.execute(new callbackrunnable(callback, callbackexecutor, errorhandler) {
  @override public responsewrapper obtainresponse() {
   return (responsewrapper) invokerequest(interceptortape, methodinfo, args);
  }
 });
 
 return null; // asynchronous methods should have return type of void.
}

执行请求时会调用resthandler的invoke方法,如上所示,主要是上面代码中标注有6点

1.如果调用的是object的方法,不做处理直接调用。
2.通过getmethodinfo获取调用的method对应的restmethodinfo,前面说了,构造resthandler对象时传进来了一个method->restmethodinfo的映射,初始时是空的。

static restmethodinfo getmethodinfo(map<method, restmethodinfo> cache, method method) {
  synchronized (cache) {
   restmethodinfo methodinfo = cache.get(method);
   if (methodinfo == null) {
    methodinfo = new restmethodinfo(method);
    cache.put(method, methodinfo);
   }
   return methodinfo;
  }

在getmethodinfo中判断如果相应的映射不存在,就建立这个映射,并如名字所示缓存起来

3. 如果是同步调用(接口中直接返回数据,不通过callback或observe),直接调用invokerequest

4. 如果是非同步调用,先通过requestinterceptortape记录拦截请求,记录后在后台线程做实际拦截,后面会提到。

5. 如果是observe请求(rxjava),执行第5步,对rxjava不了解,略过

6. 如果是callback形式,交由线程池执行

接口中的每一个method有一个对应的restmethodinfo,关于接口中annotation信息的处理就都在这里了

restmethodinfo

private enum responsetype {
  void,
  observable,
  object
}
restmethodinfo(method method) {
  this.method = method;
  responsetype = parseresponsetype();
  issynchronous = (responsetype == responsetype.object);
  isobservable = (responsetype == responsetype.observable);
}

在构造函数中调用了parseresponsetype,parseresponsetype解析了方法签名,根据方法的返回值类型及最后一个参数的类型判断方法的类型是哪种responsetype

无论是哪种responsetype,最终都是调用invokerequest执行实际的请求,接下来依次看下invokerequest的执行步骤

restadapter.invokerequest

第一步是调用methodinfo.init()解析调用的方法,方法里有做判断,只在第一次调用时解析,因为处一次解析后这个对象就被缓存起来了,下次调同一个方法时可以直接使用

 synchronized void init() {
  if (loaded) return;

  parsemethodannotations();
  parseparameters();

  loaded = true;
 }

在restmethodinfo.init中分别调用

  • parsemethodannotations():解析所有方法的annotation
  • parseparameters():解析所有参数的annotation
for (annotation methodannotation : method.getannotations()) {
 class<? extends annotation> annotationtype = methodannotation.annotationtype();
 restmethod methodinfo = null;
 // look for a @restmethod annotation on the parameter annotation indicating request method.
 for (annotation innerannotation : annotationtype.getannotations()) {
  if (restmethod.class == innerannotation.annotationtype()) {
   methodinfo = (restmethod) innerannotation;
   break;
  }
 }
 ...
}

在parsemethodannotations中,会获取方法所有的annotation并遍历:

  • 对于每一个annotation,也会获取它的annotation,看它是否是被restmethod注解的annotation,如果是,说明是@get,@post类型的注解,就调用parsepath解析请求的url,requestparam(url中问号后的内容)及url中需要替换的参数名(url中大括号括起来的部分)
  • 寻找headers annotation解析header参数
  • 解析requesttype:simple,multipart,form_url_encoded

parseparameters解析请求参数,即参数的annotation,@path、@header、@field等

第二步是requestbuilder和interceptor,这两个是有关联的,所以一起看。

requestbuilder requestbuilder = new requestbuilder(serverurl, methodinfo, converter);
requestbuilder.setarguments(args);
requestinterceptor.intercept(requestbuilder);
request request = requestbuilder.build();

先说requestinterceptor,作用很明显,当执行请求时拦截请求以做一些特殊处理,比如添加一些额外的请求参数。

/** intercept every request before it is executed in order to add additional data. */
public interface requestinterceptor {
 /** called for every request. add data using methods on the supplied {@link requestfacade}. */
 void intercept(requestfacade request);

 interface requestfacade {
  void addheader(string name, string value);
  void addpathparam(string name, string value);
  void addencodedpathparam(string name, string value);
  void addqueryparam(string name, string value);
  void addencodedqueryparam(string name, string value);
 }

 /** a {@link requestinterceptor} which does no modification of requests. */
 requestinterceptor none = new requestinterceptor() {
  @override public void intercept(requestfacade request) {
   // do nothing.
  }
 };
}

requestinterceptor只有一个方法intercept,接收一个requestfacade参数,requestfacade是requestinterceptor内部的一个接口,这个接口的方法就是添加请求参数,query、header什么的。大概可以看出requestinterceptor的作用了,如果requestfacade表示一个请求相关的数据,requestinteceptor.intercept的作用就是向这个requestfacade中添加额外header,param等参数。

requestfacade的一个子类叫requestbuilder,用来处理request请求参数,在invokerequest中会对requestbuilder调用intercept方法向requestbuilder添加额外的参数。

有一个叫requestinterceptortape的类,同时实现了requestfacade与requestinterceptor,它的作用是:

  • 当作为requestfacade使用时作为参数传给一个requestinteceptor,这个requestinterceptor调用它的addheader等方法时,它把这些调用及参数记录下来
  • 然后作为requestinterceptor使用时,将之前记录的方法调用及参数重新应用到它的intercept参数requestfacade中

在resthandler.invoke中,如果判断方法的调用不是同步调用,就通过下面的两行代码将用户设置的interceptor需要添加的参数记录到requestinterceptortape,然后在invokerequest中再实际执行参数的添加。

// apply the interceptor synchronously, recording the interception so we can replay it later.
// this way we still defer argument serialization to the background thread.
final requestinterceptortape interceptortape = new requestinterceptortape();
requestinterceptor.intercept(interceptortape);

requestbuilder.setarguments()解析调用接口时的实际参数。然后通过build()方法生成一个request对象

第三步执行请求,response response = clientprovider.get().execute(request);

第四步就是解析并分发请求结果了,成功请求时返回结果,解析失败调用errorhandler给用户一个自定义异常的机会,但最终都是通过异常抛出到invoke()中的,如果是同步调用,直接抛异常,如果是callback调用,会回调callback.failure

callbackrunnable

请求类型有同步请求,callback请求,observable请求,来看下callback请求:

callback<?> callback = (callback<?>) args[args.length - 1];
httpexecutor.execute(new callbackrunnable(callback, callbackexecutor, errorhandler) {
  @override public responsewrapper obtainresponse() {
   return (responsewrapper) invokerequest(interceptortape, methodinfo, args);
  }
});

 callback请求中函数最后一个参数是一个callback的实例,httpexecutor是一个executor,用于执行runnable请求,我们看到,这里new了一个callbackrunnable执行,并实现了它的obtainresponse方法,看实现:

abstract class callbackrunnable<t> implements runnable {
 private final callback<t> callback;
 private final executor callbackexecutor;
 private final errorhandler errorhandler;

 callbackrunnable(callback<t> callback, executor callbackexecutor, errorhandler errorhandler) {
  this.callback = callback;
  this.callbackexecutor = callbackexecutor;
  this.errorhandler = errorhandler;
 }

 @suppresswarnings("unchecked")
 @override public final void run() {
  try {
   final responsewrapper wrapper = obtainresponse();
   callbackexecutor.execute(new runnable() {
    @override public void run() {
     callback.success((t) wrapper.responsebody, wrapper.response);
    }
   });
  } catch (retrofiterror e) {
   throwable cause = errorhandler.handleerror(e);
   final retrofiterror handled = cause == e ? e : unexpectederror(e.geturl(), cause);
   callbackexecutor.execute(new runnable() {
    @override public void run() {
     callback.failure(handled);
    }
   });
  }
 }

 public abstract responsewrapper obtainresponse();
} 

就是一个普通的runnable,在run方法中首先执行obtailresponse,从名字可以看到是执行请求返回response,这个从前面可以看到执行了invokerequest,和同步调用中一样执行请求。

紧接着就提交了一个runnable至callbackexecutor,在看platform时看到了callbackexecotor是通过platform.get().defaultcallbackexecutor()返回的,android中是向主线程的一个handler发消息

值得注意的事,对于同步调用,如果遇到错误是直接抛异常,而对于异步调用,是调用callback.failure()

mime

执行网络请求,需要向服务端发送请求参数,如表单数据,上传的文件等,同样需要解析服务端返回的数据,在retrofit中对这些做了封装,位于mime包中,也只有封装了,才好统一由指定的converter执行数据的转换

typedinput和typedoutput表示输入输出的数据,都包含mimetype,并分别支持读入一个inputstream或写到一个outputstrem

/**
 * binary data with an associated mime type.
 *
 * @author jake wharton (jw@squareup.com)
 */
public interface typedinput {

 /** returns the mime type. */
 string mimetype();

 /** length in bytes. returns {@code -1} if length is unknown. */
 long length();

 /**
  * read bytes as stream. unless otherwise specified, this method may only be called once. it is
  * the responsibility of the caller to close the stream.
  */
 inputstream in() throws ioexception;
}

/**
 * binary data with an associated mime type.
 *
 * @author bob lee (bob@squareup.com)
 */
public interface typedoutput {
 /** original filename.
  *
  * used only for multipart requests, may be null. */
 string filename();

 /** returns the mime type. */
 string mimetype();

 /** length in bytes or -1 if unknown. */
 long length();

 /** writes these bytes to the given output stream. */
 void writeto(outputstream out) throws ioexception;
}

typedbytearray,内部数据是一个byte数组

 

private final byte[] bytes;

 @override public long length() {
  return bytes.length;
 }

 @override public void writeto(outputstream out) throws ioexception {
  out.write(bytes);
 }

 @override public inputstream in() throws ioexception {
  return new bytearrayinputstream(bytes);
 }

typedstring,继承自typedbytearray,内部表示是一样的

public typedstring(string string) {
  super("text/plain; charset=utf-8", converttobytes(string));
 }

 private static byte[] converttobytes(string string) {
  try {
   return string.getbytes("utf-8");
  } catch (unsupportedencodingexception e) {
   throw new runtimeexception(e);
  }
 }

其他的也一样,从名字很好理解:typedfile,multiparttypedoutput,formencodedtypedoutput。

其他

retrofit对输入和输出做了封装,通过typedoutput向服务器发送数据,通过typedinput读取服务器返回的数据。

通过multiparttypedoutput支持文件上传,读取服务器数据时,如果要求直接返回未解析的response,restonse会被转换为typedbytearray,所以不能是大文件类的

retrofit支持不同的log等级,当为loglevel.full时会把request及response的body打印出来,所以如果包含文件就不行了。

retrofit默认使用gsonconverter,所以要想获取原始数据不要retrofit解析,要么自定义conveter,要么直接返回response了,返回response也比较麻烦

总体来说retrofit看起来很好用,不过要求服务端返回数据最好要规范,不然如果请求成功返回一种数据结构,请求失败返回另一种数据结构,不好用converter解析,接口的定义也不好定义,除非都返回response,或自定义converter所有接口都返回string

在twitter上jakewharton这么说:

gearing up towards a retrofit 1.6.0 release and then branching 1.x so we can push master towards a 2.0 and fix long-standing design issues.

要出2.0了,内部api会改,接口应该不怎么变

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

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

相关文章:

验证码:
移动技术网