温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Retrofit2的使用

发布时间:2020-07-11 09:14:08 来源:网络 阅读:1188 作者:墨宇hz 栏目:移动开发

Retrofit2

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

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<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories);
  adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));

  // Make a defensive copy of the converters.
  List<Converter.Factory> 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<ResponseBody> getGithubApi();
}

定义一个接口信息。Retrofit2中访问的一个网络接口,返回的都是一个Call<ResponseBody> 实例,准确的说是Call<T>实例,但是这个实例中并没有在实例化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<String, String> params)//其中params的key作为参数名,value作为参数的值。

常用的注解表格

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

比如:使用HTTP注解

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

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

标记在形参之前:

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

2.4. 访问数据。

ApiService githubService = retrofit.create(ApiService.class);
Call<ResponseBody> githubApi = githubService.getGithubApi();
Response<ResponseBody> 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<ResponseBody> githubApi = githubService.getGithubApi();
    Response<ResponseBody> 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")
    }

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI