Retrofit 学习笔记

参考:

  • 网络加载框架 - Retrofit
  • 这是一份很详细的 Retrofit 2.0 使用教程(含实例讲解)
  • Android:Retrofit 与 RxJava联合使用大合集(含实例教程)!

使用流程

  1. 添加依赖
    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
  1. 添加网络权限

  1. 创建接收服务器返回数据的类
public class Persion {
    ...
    // 根据返回数据的格式和数据解析方式(Json、XML等)定义
    // 下面会在实例进行说明
}
  1. 创建用于描述网络请求的接口
public interface GetRequest_Interface {

    @GET("persion")
    Call  getPersion();
    // @GET注解的作用:采用Get方法发送网络请求

    // getCall() = 接收网络请求数据的方法
    // 其中返回类型为Call<*>,*是接收数据的类(即上面定义的Persion类)
    // 如果想直接获得Responsebody中的内容,可以定义网络请求返回值为Call
  1. 创建Retrofit对象
Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("address/")   //设置网络请求的URL地址
                .addConverterFactory(GsonConverterFactory.create())   //设置数据解析器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 支持RxJava平台
                .build();

完整的URL地址=baseUrl+@GET()中的参数
上面的请求地址:address/persion
有一点注意如果是本机测试不要用localhost和127.0.0.1
还可以用动态传递请求参数
ConverterFactory和CallAdapterFactory请往后看

  1. 创建网络请求接口实例 并 配置网络请求参数
GetPersion_Interface getPersion_interface=retrofit.create(GetPersion_Interface.class);

        Call call=getPersion_interface.getPersion();
  1. 发送网络请求(异步 / 同步)
call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                textView.setText("Id:"+response.body().getId()+" "+"Name:"+response.body().getName()+" "+"Age:"+response.body().getAge());
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                textView.setText("请求失败");
            }
        });

这里采用异步操作
在这里有一个注意点,如果要返回ResponseBody的话,response.body().string()而不是toString

注解类型

网络请求方法注解

注解 解释
@GET 请求指定的页面信息,并返回实体主体
@POST 向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。数据被包含在请求体中。POST请求可能会导致新的资源的建立和/或已有资源的修改
@PUT 从客户端向服务器传送的数据取代指定的文档的内容
@HEAD 类似于get请求,只不过返回的响应中没有具体的内容,用于获取报头
@DELETE 请求服务器删除指定的页面
@CONNECT HTTP/1.1协议中预留给能够将连接改为管道方式的代理服务器。
@OPTIONS 允许客户端查看服务器的性能。
@HTTP 用于替换以上7个注解的作用以及更多功能拓展
  • @HTTP描述
    如下:
public interface GetRequest_Interface {
    /**
     * method:网络请求的方法(区分大小写)
     * path:网络请求地址路径
     * hasBody:是否有请求体
     */
    @HTTP(method = "GET", path = "blog/{id}", hasBody = false)
    Call getCall(@Path("id") int id);
    // {id} 表示是一个变量
    // method 的值 retrofit 不会做处理,所以要自行保证准确
}

标记类注解

注解 解释
@FormUrlEncoded 表示请求体是一个Form表单
@Multipart 表示请求体是一个支持文件上传的Form表单
@Streaming 表示数据以流的形式返回,适用于返回数据大的情况(如果没有该注解,默认把数据全部载入内存,之后获取数据也是从内存中提取)
  • @FormUrlEncoded

表示发送form-encoded的数据
每个键值对需要用@Filed来注解键名,随后的对象需要提供值。

  • @Multipart

作用:表示发送form-encoded的数据(适用于 有文件 上传的场景)
每个键值对需要用@Part来注解键名,随后的对象需要提供值。
具体使用如下:
GetRequest_Interface

public interface GetRequest_Interface {
        /**
         *表明是一个表单格式的请求(Content-Type:application/x-www-form-urlencoded)
         * Field("username") 表示将后面的 String name 中name的取值作为 username 的值
         */
        @POST("/form")
        @FormUrlEncoded
        Call testFormUrlEncoded1(@Field("username") String name, @Field("age") int age);

        /**
         * {@link Part} 后面支持三种类型,{@link RequestBody}、{@link okhttp3.MultipartBody.Part} 、任意类型
         * 除 {@link okhttp3.MultipartBody.Part} 以外,其它类型都必须带上表单字段({@link okhttp3.MultipartBody.Part} 中已经包含了表单字段的信息),
         */
        @POST("/form")
        @Multipart
        Call testFileUpload1(@Part("name") RequestBody name, @Part("age") RequestBody age, @Part MultipartBody.Part file);

}

// 具体使用
       GetRequest_Interface service = retrofit.create(GetRequest_Interface.class);
        // @FormUrlEncoded 
        Call call1 = service.testFormUrlEncoded1("Carson", 24);

        //  @Multipart
        RequestBody name = RequestBody.create(textType, "Carson");
        RequestBody age = RequestBody.create(textType, "24");

        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", "test.txt", file);
        Call call3 = service.testFileUpload1(name, age, filePart);

网络请求参数注解

注解 解释
@Headers 添加请求头(注释在方法上)
@Header 添加不固定值的请求头(用在参数中)
@Body 用于非表单请求体( 不能用在get 请求方法)
@Field 向Post表单传入键值对
@FieldMap 向Post表单传入键值对(多个)
@Part 用于表单字段,适用于有文件上传的情况
@PartMap 用于表单字段,适用于有文件上传的情况
@Query 用于表单字段用在get方法上
@QueryMap 用于表单字段用在get方法上
@Path URL缺省值
@URL URL设置

@Field @Body一般用于Post方法,参数在请求体里
@Query 用在get方法,参数在请求头

  • @Header & @Headers

添加请求头 &添加不固定的请求头

// @Header
@GET("user")
Call getUser(@Header("Authorization") String authorization)

// @Headers
@Headers("Authorization: authorization")
@GET("user")
Call getUser()

// 以上的效果是一致的。
// 区别在于使用场景和使用方式
// 1. 使用场景:@Header用于添加不固定的请求头,@Headers用于添加固定的请求头
// 2. 使用方式:@Header作用于方法的参数;@Headers作用于方法
  • @Body

以 Post方式 传递 自定义数据类型 给服务器,类的实例啥的
特别注意:如果提交的是一个Map,那么作用相当于 @Field
不过Map要经过 FormBody.Builder 类处理成为符合 Okhttp 格式的表单,如:

FormBody.Builder builder = new FormBody.Builder();
builder.add("key","value");
  • @Field & @FieldMap

发送 Post请求 时提交请求的表单字段
具体使用:与 @FormUrlEncoded 注解配合使用

public interface GetRequest_Interface {
        /**
         *表明是一个表单格式的请求(Content-Type:application/x-www-form-urlencoded)
         * Field("username") 表示将后面的 String name 中name的取值作为 username 的值
         */
        @POST("/form")
        @FormUrlEncoded
        Call testFormUrlEncoded1(@Field("username") String name, @Field("age") int age);

/**
         * Map的key作为表单的键
         */
        @POST("/form")
        @FormUrlEncoded
        Call testFormUrlEncoded2(@FieldMap Map map);

}

// 具体使用
         // @Field
        Call call1 = service.testFormUrlEncoded1("Carson", 24);

        // @FieldMap
        // 实现的效果与上面相同,但要传入Map
        Map map = new HashMap<>();
        map.put("username", "Carson");
        map.put("age", 24);
        Call call2 = service.testFormUrlEncoded2(map);
  • @Part & @PartMap

发送 Post请求 时提交请求的表单字段
与@Field的区别:功能相同,但携带的参数类型更加丰富,包括数据流,所以适用于 有文件上传 的场景 与 @Multipart 注解配合使用

public interface GetRequest_Interface {

          /**
         * {@link Part} 后面支持三种类型,{@link RequestBody}、{@link okhttp3.MultipartBody.Part} 、任意类型
         * 除 {@link okhttp3.MultipartBody.Part} 以外,其它类型都必须带上表单字段({@link okhttp3.MultipartBody.Part} 中已经包含了表单字段的信息),
         */
        @POST("/form")
        @Multipart
        Call testFileUpload1(@Part("name") RequestBody name, @Part("age") RequestBody age, @Part MultipartBody.Part file);

        /**
         * PartMap 注解支持一个Map作为参数,支持 {@link RequestBody } 类型,
         * 如果有其它的类型,会被{@link retrofit2.Converter}转换,如后面会介绍的 使用{@link com.google.gson.Gson} 的 {@link retrofit2.converter.gson.GsonRequestBodyConverter}
         * 所以{@link MultipartBody.Part} 就不适用了,所以文件只能用 @Part MultipartBody.Part 
         */
        @POST("/form")
        @Multipart
        Call testFileUpload2(@PartMap Map args, @Part MultipartBody.Part file);

        @POST("/form")
        @Multipart
        Call testFileUpload3(@PartMap Map args);
}

// 具体使用
 MediaType textType = MediaType.parse("text/plain");
        RequestBody name = RequestBody.create(textType, "Carson");
        RequestBody age = RequestBody.create(textType, "24");
        RequestBody file = RequestBody.create(MediaType.parse("application/octet-stream"), "这里是模拟文件的内容");

        // @Part
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", "test.txt", file);
        Call call3 = service.testFileUpload1(name, age, filePart);
        ResponseBodyPrinter.printResponseBody(call3);

        // @PartMap
        // 实现和上面同样的效果
        Map fileUpload2Args = new HashMap<>();
        fileUpload2Args.put("name", name);
        fileUpload2Args.put("age", age);
        //这里并不会被当成文件,因为没有文件名(包含在Content-Disposition请求头中),但上面的 filePart 有
        //fileUpload2Args.put("file", file);
        Call call4 = service.testFileUpload2(fileUpload2Args, filePart); //单独处理文件
        ResponseBodyPrinter.printResponseBody(call4);
}
  • @Query和@QueryMap

用于 @GET 方法的查询参数(Query = Url 中 ‘?’ 后面的 key-value)
如:url = http://www.println.net/?cate=android,其中,Query = cate
具体使用:配置时只需要在接口方法中增加一个参数即可:

   @GET("/")    
   Call cate(@Query("cate") String cate);
}

// 其使用方式同 @Field与@FieldMap,这里不作过多描述
  • @Path

URL地址的缺省值,用@Path注解标志要传到url中{ }的变量
如:

public interface GetRequest_Interface {

        @GET("users/{user}/repos")
        Call  getBlog(@Path("user") String user );
        // 访问的API是:https://api.github.com/users/{user}/repos
        // 在发起请求时, {user} 会被替换为方法的第一个参数 user(被@Path注解作用)
    }
  • @Url

直接传入一个请求的 URL变量 用于URL设置

public interface GetRequest_Interface {

        @GET
        Call testUrlAndQuery(@Url String url, @Query("showAll") boolean showAll);
       // 当有URL注解时,@GET传入的URL就可以省略
       // 当GET、POST...HTTP等方法中没有设置Url时,则必须使用 {@linlk Url}提供

}

数据解析器(Converter)

Retrofit支持多种数据解析方式
使用时需要在Gradle添加依赖

数据解析器 Gradle依赖
Gson implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
Jackson implementation 'com.squareup.retrofit2:converter-jackson:2.4.0'
Simple XML implementation 'com.squareup.retrofit2:converter-simplexml:2.0.2'
Protobuf implementation 'com.squareup.retrofit2:converter-protobuf:2.4.0'
Moshi implementation 'com.squareup.retrofit2:converter-moshi:2.4.0'
Wire implementation 'com.squareup.retrofit2:converter-wire:2.4.0'
Scalars implementation 'com.squareup.retrofit2:converter-scalars:2.4.0'

网络请求适配器(CallAdapter)

  • Retrofit支持多种网络请求适配器方式:guava、Java8和rxjava

使用时如使用的是 Android 默认的 CallAdapter,则不需要添加网络请求适配器的依赖,否则则需要按照需求进行添加 Retrofit 提供的 CallAdapter

  • 使用时需要在Gradle添加依赖:
网络请求适配器 Gradle依赖
rxjava implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
Java8 implementation 'com.squareup.retrofit2:adapter-java8:2.4.0'
guava implementation 'com.squareup.retrofit2:adapter-guava:2.4.0'

发送网络请求

封装了 数据转换、线程切换的操作

//发送网络请求(异步)
        call.enqueue(new Callback() {
            //请求成功时回调
            @Override
            public void onResponse(Call call, Response response) {
                //请求处理,输出结果
                response.body().show();
            }

            //请求失败时候的回调
            @Override
            public void onFailure(Call call, Throwable throwable) {
                System.out.println("连接失败");
            }
        });

// 发送网络请求(同步)
Response response = call.execute();

你可能感兴趣的:(Retrofit 学习笔记)