资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Retrofit2的使用-创新互联

Retrofit2

Android常用的网络访问HttpClient, HttpUrlConnection,OkHttp(okgo),xUtils, Volley等. Android4.4之后使用OkHttp作为HttpUrlConnection底层实现。这次讲一下Retrofit2怎么使用。

成都创新互联公司-专业网站定制、快速模板网站建设、高性价比陇西网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式陇西网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖陇西地区。费用合理售后完善,十年实体公司更值得信赖。

Retrofit2实际上是通过注解的方式对okhttp又一次封装。

  1. 在AndroidStudio项目中,添加Retrofit2的依赖。

    compile 'com.squareup.retrofit2:retrofit:2.3.0'

程序构建成功后,查看项目具体依赖了多少jar包。

com.squareup.okhttp3:okhttp:3.8.0
com.squareup.okio:okio:1.13.0
com.squareup.retrofit2:retrofit:2.3.0

retrofit2 强制依赖了okhttp3的相关库。这也说明了retrofit2底层是okhttp3具体实现的。okhttp3是用来具体访问网络的,okio是squareup对Java的io/nio的补充,使其更容易访问,存储和处理数据。okio主要功能封装到了ByteString和Buffer里面了。

  1. 简单的网络访问(以https://suggest.taobao.com/sug?code=utf-8&q=java&callback=cb为例)。

2.1. 首先实例化okhttp

OkHttpClient client = new OkHttpClient.Builder().build();
//实例化OkHttpClient的时候,还可以设置拦截器,缓存,认证信息,网络拦截器,连接池,超时时间等信息。

2.2. 其次实例化retrofit,并将实例化好的okhttp3关联到retrofit2。

Retrofit retrofit = new Retrofit.Builder().client(client).baseUrl("https://suggest.taobao.com/").build();

2.2.1 ...build()方法:

public Retrofit build() {
  if (baseUrl == null) {
    throw new IllegalStateException("Base URL required.");
  }

  okhttp3.Call.Factory callFactory = this.callFactory;
  if (callFactory == null) {
    callFactory = new OkHttpClient();
  }

  Executor callbackExecutor = this.callbackExecutor;
  if (callbackExecutor == null) {
    callbackExecutor = platform.defaultCallbackExecutor();
  }

  // Make a defensive copy of the adapters and add the default Call adapter.
  List adapterFactories = new ArrayList<>(this.adapterFactories);
  adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));

  // Make a defensive copy of the converters.
  List converterFactories = new ArrayList<>(this.converterFactories);

  return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
      callbackExecutor, validateEagerly);
}

从这个方法里面可以看出,在实例化Retrofit的时候,baseUrl这个变量是必须要设置的,否则直接抛出IllegalStateException;而其余的一些信息如果不进行,程序里面会给设置一个默认的信息.默认给设置了OkHttpClient实例,OkHttp3连接池、解析工厂、CallAdapter等信息;然后返回了一个retrofit2实例。

2.3. 定义接口文件ApiService。

interface ApiService{
    @GET("sug?code=utf-8&q=java&callback=cb")
    Call getGithubApi();
}

定义一个接口信息。Retrofit2中访问的一个网络接口,返回的都是一个Call 实例,准确的说是Call实例,但是这个实例中并没有在实例化Retrofit2中设置addConverterFactory方法,如果需要解析成具体的JavaBean,则又需要依赖 'com.squareup.retrofit2:converter-gson:2.0.2', 'com.google.code.gson:gson:2.3.1'。当然再配合rxjava,rxandroid来使用的话,将是Android平台很流行的网络访问框架,三者的整合封装本文不讲。

Retrofit2中支持多种注解来定义http网络访问,比如:POST,GET,DELETE,PUT;还支持多种标记注解FormUrlEncoded(使用到的注解都放到了retrofit2.http包下)

已2.3 ApiService接口为例。这个接口中定义了一个getGithubApi方法,该方法使用get方式提交,具体的路径则写到@GET("sug?code=utf-8&q=java&callback=cb"),我们知道get方式提交参数是直接将参数拼接到url地址后面。同样也可以使用POST注解,表示该表单使用POST方式提交参数,要提交的参数则需要传入到方法里面了,该方法就应该这么定义getGithubApi(@Field("code") String code,@Field("q") String q,@Field("callback") String callback)或者getGithubApi(@FieldMap Map params)//其中params的key作为参数名,value作为参数的值。

常用的注解表格

标记在方法名之上
序号
名称 备注
1GET表示该方法使用GET方式提交参数。
2POST表示该方法使用POST方式提交参数,这个经常和参数标记@Field和@FieldMap组合使用,也配合方法标记@FormUrlEncoded使用。
3PUT
4DELETE
5PATCH
6HEAD
7OPTIONS
8HTTP更加灵活的标记,这个标记里面可以指定,提交方式,path值,是否有body。
9Streaming返回流数据,当服务器返回的数据过大时使用

比如:使用HTTP注解

@HTTP(method = "get", path = "zzhhz/{id}", hasBody = false)
Call getBlog(@Path("id") int id);

这里面指定了提交方式,path路径,是否有body体。在这个地方path="zzhhz/{id}",id是不确定的,又要当一个参数传进去,用{}标记变量,然后使用Path注解标记在方法形参前。

标记在形参之前:

序号 名称 备注
1Field/FieldMap这个参数注解经常配合POST注解使用,因为POST是隐式提交参数。
2Part/PartMap这个经常是表示提交文件,又和Multipart,POST注解配合使用。
3Pathurl路径,如上边HTTP注解示例
4Query/QueryMap/QueryName查询参数,通常配合GET注解使用

2.4. 访问数据。

ApiService githubService = retrofit.create(ApiService.class);
Call githubApi = githubService.getGithubApi();
Response execute = githubApi.execute();
if (execute != null && execute.isSuccessful()){
    String string = execute.body().string();
    System.out.println(string);
} else {
    System.out.println("访问失败");
}

之前说过Retrofit2强制依赖了OkHttp3, 在2.2实例化Retrofit2的时候,将已实例化的OkHttpClient传入进Retrofit2里,供其进行网络访问。

Retrofit2和OkHttp3实例化过程中使用到了建造者模式(不赘述涉及模式)。

  1. 完整的网络访问设置:添加上拦截器(基于Java项目,开发工具IDEA)。

    @Test
    public void testRetrofit() throws IOException {
    //https://suggest.taobao.com/sug?code=utf-8&q=java&callback=cb

    OkHttpClient client = new OkHttpClient.Builder().addInterceptor((chain) -> {
        Request request = chain.request();
        return chain.proceed(request);
    }).readTimeout(60, TimeUnit.SECONDS).writeTimeout(60, TimeUnit.SECONDS).build();
    
    Retrofit retrofit = new Retrofit.Builder().client(client).baseUrl("https://suggest.taobao.com/").build();
    
    ApiService githubService = retrofit.create(ApiService.class);
    Call githubApi = githubService.getGithubApi();
    Response execute = githubApi.execute();
    if (execute != null && execute.isSuccessful()) {
        String string = execute.body().string();
        System.out.println(string);
    } else {
        System.out.println("访问失败");
    }

    }

    interface ApiService {@GET("sug?code=utf-8&q=java&callback=cb")
    br/>@GET("sug?code=utf-8&q=java&callback=cb")
    getGithubApi();
    }

到此Retrofit2讲解完毕。语言组织的不好,有什么问题大家可以留言,相互学习。

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


标题名称:Retrofit2的使用-创新互联
本文来源:http://cdkjz.cn/article/cociep.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220