人人都会用Retrofit——为新人引路

271 阅读4分钟

简介

Retrofit是Square公司开发的一款针对Android网络请求的框架,Retrofit底层是基于OkHttp实现的。与其他网络框架不同的是,它更多使用运行时注解的方式提供功能。对于追求代码精简、直观的程序员来讲,这个框架最好不过了。 本文主要为了让新手入门,所以只会说一下移动开发中常用到的。

使用

首先还是先引入依赖库

compile 'com.squareup.retrofit2:retrofit:2.1.0'  
compile 'com.squareup.retrofit2:converter-gson:2.1.0'  

第二个是为了增加支持返回值为Gson类型数据所需的依赖包。
不要忘记在manifest添加网络权限

Retrofit注解分类

三大类。请求方法注解、标记类注解、参数类注解。
请求方法注解常用的是:GET、POST。
标记类注解常用的是:FormUrlEncoded
参数类注解常用的是:Header、Headers、Body、Path、Field、FieldMap、Query、QueryMap

接下来我们开始使用
现在我们需要请求网络接口 http://www.baidu.com/getInfo
由于现在没有什么稳定的公共API,这里随便写了一个,我一般通过Charles模拟返回的数据,关于Charles的使用可以查看我之前的文章网络开发的利器,初识Charles
使用之前我们要先定义一个interface,用来写网络接口。

public interface IpService {
    @GET("getInfo")
    Call<NetModel> getResult();
}

@GET中的内容是在请求时拼在BaseUrl后面的,NetModel是自己写的一个接收返回数据的实体

然后我们创建出来一个Retrofit对象

public Retrofit getRetrofit() {
    // baseUrl,必须有
    String url = "http://www.baidu.com"
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create())// 这里用的就是开始引入的gson依赖包
            .build();
    return retrofit;
}

然后请求网络

public void callApi() {
    // 根据我们刚刚创建的接口,用retrofit生成一个实例
    IpService ipService = getRetrofit().create(IpService.class);
    Call<NetModel> call = ipService.getResult();
    call.enqueue(new CallBack<NetModel>(){
       @Override
       public void onResponse(Call<NetModel> call,Response<NetModel> response){
            // 请求成功,拿到返回数据 
            NetModel result = response.body().getData();
       }
       @Override
       public void onFailure(Call<NewModel> call,Throwable t){
           
       }
    });
}

不错,就是这么简单,当然这个例子还没有参数,只是GET请求,下面我们说下加参数和POST请求,这些都仅仅需要在定义的IpService接口中使用注解就可以完成。

使用其他注解

情况1:调用路径可变,使用@Path注解

public interface IpService {
    @GET("getInfo/{path}")
    Call<NetModel> getResult(@Path("path") String path);
}

传入参数path,会映射到注解中的path,就是拼在baseurl后面的路径

情况2:调用参数可变,使用@Query注解

public interface IpService {
    @GET("getInfo")
    Call<NetModel> getResult(@Query("name") String x);
    
    @GET("getInfo")
    Call<NetModel> getResult(@Query("name") String x, @Query("age") String y);
}

传入参数name,相当于请求时拼接在后面getInfo?name=x
当然可以多参数,相当于拼接了getInfo?name=x&age=y

情况3:调用参数较多,使用@QueryMap注解

public interface IpService {
    @GET("getInfo")
    Call<NetModel> getResult(@QueryMap Map<String,String> map);
}

一个道理,传进一个map,会依次拼接在path后面

情况4:使用POST请求

在POST请求中,我们使用@Field注解传递键值对

public interface IpService {
    @FormUrlEncoded
    @POST("getInfo")
    Call<NetModel> getResult(@Field("name") String x);
    
    @FormUrlEncoded
    @POST("getInfo")
    Call<NetModel> getResult(@Field("name") String x,@Field("age") String y);
}

@FormUrlEncoded注解表明这是一个表单请求,@Field注解类似@Query,用于在POST请求中传递参数,当然可以同时传多个。@FieldMap同理于@QueryMap

情况5:需要用POST提交一个JSON字符串,使用@Body注解

public interface IpService {
    @POST("getInfo")
    Call<NetModel> getResult(@Body User user);
}
public class User {

    private String name;
    private int age;
    
    public User(String name,int age){
        this.name = name;
        this.age = age;
    }
}

用@Body注解标识,Retrofit会将User对象转换为字符串。 然后请求网络

public void callApi() {
    IpService ipService = getRetrofit().create(IpService.class);
    Call<NetModel> call = ipService.getResult();
    call.enqueue(new CallBack<NetModel>(){
       ...
    });
}

情况6:有时候还需要添加消息报头Header,可以用@Headers

public interface IpService {
    @GET("getInfo")
    @Headers({
        "Accept-Encoding:application/json",
        "User-Agent:Retrofit",
        "Aaa:bbb"
    })
    Call<NetModel> getResult();
}

还可以用@Header动态添加

public interface IpService {
    @GET("getInfo")
    Call<NetModel> getResult(@Header("Location") String location);
}

上面列举这些基本涵盖了移动开发的基本情况,前面也说了,本文只在为了新手入门,熟练使用之后可以自己尝试封装,或是结合RxJava使用,写的不明白的欢迎留言,内容较为简单,还望大佬轻喷 - -!