Android 高

Retrofit2 简略讲解

2019-05-16  本文已影响0人  穿越平行宇宙

一、Retrofit2 概述

1, Retrofit框架是Square公司出品的目前非常流行的网络框架.
效率高,实现简单,运用注解和动态代理.
极大简化了网络请求的繁琐步骤,非常适合REST ful网络请求.
目前Retofit版本是2

2, Retrofit其实我们可以理解为OkHttp的加强版。
它也是一个网络加载框架。底层是使用OKHttp封装的。
准确来说,网络请求的工作本质上是OkHttp完成,而 Retrofit 仅负责网络请求接口的封装。
它的一个特点是包含了特别多注解,方便简化你的代码量。
并且还支持很多的开源库(著名例子:Retrofit + RxJava)

二、Retrofit2 的好处

1,超级解耦
解耦?解什么耦?
我们在请求接口数据的时候,API接口定义和API接口使用总是相互影响,什么传参、回调等,耦合在一块。有时候我们会考虑一下怎么封装我们的代码让这两个东西不那么耦合,这个就是Retrofit的解耦目标,也是它的最大的特点。
2,可以配置不同HttpClient来实现网络请求,如OkHttp、HttpClient...
3,支持同步、异步和RxJava
4,可以配置不同的反序列化工具来解析数据,如json、xml...
5,请求速度快,使用非常方便灵活

三、Retrofit2 配置

1,官网:http://square.github.io/retrofit/
2,依赖:

implementation 'com.squareup.retrofit2:retrofit:2.5.0'

3,OkHttp库依赖
由于Retrofit是基于OkHttp,所以还需要添加OkHttp库依赖

//日志拦截器
compile 'com.squareup.okhttp3:logging-interceptor:3.5.0'
implementation 'com.squareup.okhttp3:okhttp:3.12.0'

4,添加网络权限

<uses-permission android:name="android.permission.INTERNET" />

四、Retrofit2 注解

注解代码       请求格式

请求方式:
    @GET           GET请求
    @POST          POST请求
    @DELETE        DELETE请求
    @HEAD          HEAD请求
    @OPTIONS       OPTIONS请求
    @PATCH         PATCH请求

请求头:
    @Headers("K:V") 添加请求头,作用于方法
    @Header("K")    添加请求头,参数添加头
    @FormUrlEncoded 用表单数据提交,搭配参数使用
    @Stream         下载
    @Multipart      用文件上传提交   multipart/form-data

请求参数:
    @Query          替代参数值,通常是结合get请求的
    @QueryMap       替代参数值,通常是结合get请求的
    @Field          替换参数值,是结合post请求的
    @FieldMap       替换参数值,是结合post请求的

请求路径:
    @Path           替换路径
    @Url            路径拼接

请求体:
    @Body(RequestBody)  设置请求体,是结合post请求的

文件处理:
    @Part Multipart.Part
    @Part("key") RequestBody requestBody(单参)
    @PartMap Map<String,RequestBody> requestBodyMap(多参)
    @Body RequestBody requestBody(自定义参数)

五、Retrofit2 的使用步骤

1,定义接口(封装URL地址和数据请求)
2,实例化Retrofit
3,通过Retrofit实例创建接口服务对象
4,接口服务对象调用接口中的方法,获取Call对象
5,Call对象执行请求(异步、同步请求)

六、Retrofit2 发送GET、POST请求(异步、同步)

  1. Get 同步请求
  2. Get 异步请求
  3. Post 同步请求
  4. Post 异步请求

七、Retrofit2其他常用注解使用

String URL = "http://api.shujuzhihui.cn/api/news/";//必须以反斜杠结尾

public interface MyServer {

    //Path
    @GET("wages/{wageId}/detail") 
    Call<ResponseBody >getImgData(@Path("wageId") String wageId);

    //Url
    @GET
    Call<ResponseBody >getImgData(@Url String url);

    @GET
    Call<ResponseBody >getImgData(@Url String url,@Query("appKey") String appkey);


    //Json
    @POST("categories")
    @Headers("Content-Type:application/json")
    Call<ResponseBody> getFormDataJson(@Body RequestBody requestBody);

    //Form
    @POST("categories")
    @Headers("Content-Type:application/x-www-form-urlencoded")
    Call<ResponseBody> getFormData1(@Body RequestBody requestBody);

    //复用URL
    @POST()
    @Headers("Content-Type:application/x-www-form-urlencoded")
    Call<ResponseBody> getFormData2(@Url String url,@Body RequestBody requestBody);

    //通用
    @POST()
    Call<ResponseBody> getFormData3(@Url String url, @Body RequestBody requestBody, @Header("Content-Type") String contentType);
}

//RequestBody参数拼接
private void initPostBody() {

    Retrofit.Builder builder = new Retrofit.Builder();
    Retrofit retrofit = builder.baseUrl(MyServer.URL)
            .build();

    MyServer myServer = retrofit.create(MyServer.class);

    //Json类型
    String json1 = "{\n" + "    \"appKey\": \"908ca46881994ffaa6ca20b31755b675\"\n" +  "}";
    RequestBody requestBody01 = RequestBody.create(MediaType.parse("application/json,charset-UTF-8"),json1);
    Call<ResponseBody> call01 = myServer.getFormDataJson(requestBody01);

    //String类型
    //有参形式
    RequestBody requestBody02 = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded,charset-UTF-8"),"appKey=908ca46881994ffaa6ca20b31755b675");
    Call<ResponseBody> call02 = myServer.getFormData1(requestBody02);

    //无参形式
    RequestBody requestBody3 = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded,charset-UTF-8"),"");
    Call<ResponseBody> call03 = myServer.getFormData1(requestBody3);

    //RequestBody (Form表单,键值对参数形式)
    //方式一(requestBody)
    FormBody requestBody = new FormBody.Builder()
            .add("appKey","908ca46881994ffaa6ca20b31755b675")
            .build();
    Call<ResponseBody> call1 = myServer.getFormData1(requestBody);

    //方式二(url+requestBody)
    FormBody requestBody = new FormBody.Builder()
            .add("appKey","908ca46881994ffaa6ca20b31755b675")
            .build();
    Call<ResponseBody> call2 = myServer.getFormData2("categories",requestBody);

    //方式三(url+requestBody+header)
    FormBody requestBody = new FormBody.Builder()
            .add("appKey","908ca46881994ffaa6ca20b31755b675")
            .build();
    Call<ResponseBody> call3 = myServer.getFormData3("categories",requestBody,"application/x-www-form-urlencoded");


    call3.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

            try {
                String result = response.body().string();

                Log.e("retrofit", "onResponse: "+result);
                tv.setText(result);//默认直接回调主线程
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {

            Log.e("retrofit", "onFailure: "+t.getMessage());
        }
    });
}

八、Retrofit2文件上传

String FileUpLoadURL = "http://yun918.cn/study/public/";

public interface MyServer {

    @POST("file_upload.php")
    @Multipart
    Call<ResponseBody> upLoadFile1(@Part MultipartBody.Part part,@Part("key") RequestBody requestBody);//单参

    @POST("file_upload.php")
    @Multipart
    Call<ResponseBody> upLoadFile2(@Part MultipartBody.Part part, @PartMap Map<String,RequestBody> requestBodyMap); //多参

    @POST("file_upload.php")
    @Multipart
    Call<ResponseBody> upLoadFile3(@Body RequestBody requestBody);  //自定义
}

//文件上传
private void initPostFile() {

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(MyServer.FileUpLoadURL)
            .build();

    MyServer myServer = retrofit.create(MyServer.class);

    Call<ResponseBody> call = null;

    //上传文件路径
    File file = new File("/sdcard/Pictures/Screenshorts/dd.png");
    if(file.exists()){

        //方式一
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("image/png"),file);

        MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody1);

        RequestBody responseBody2 = RequestBody.create(MediaType.parse("multipart/form-data"),"abc");

        call = myServer.upLoadFile1(part, responseBody2);

        //方式二
        MultipartBody.Builder builder1 = new MultipartBody.Builder().setType(MultipartBody.FORM);

        MultipartBody body = builder1.addFormDataPart("key", "abc")
                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"),file))
                .build();

        call = myServer.upLoadFile3(body);

        //方式三
        MultipartBody.Part part2 = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("image/png"),file));

        Map<String, RequestBody> map = new HashMap<>();
        RequestBody responseBody3 = RequestBody.create(MediaType.parse("multipart/form-data"),"abc");
        map.put("key",responseBody3);

        call = myServer.upLoadFile2(part2, map);

    }

    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            try {
                String result = response.body().string();

                Log.e("retrofit", "onResponse: "+result);
                tv.setText(result);//默认直接回调主线程
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.e("retrofit", "onFailure: "+t.getMessage());
        }
    });
}

九、Form表单语法

1、Form表单语法
    在Form元素的语法中,EncType表明提交数据的格式 用 Enctype 属性指定将数据回发到服务器时浏览器使用的编码类型。 
    1,application/x-www-form-urlencoded: 窗体数据被编码为名称/值对。这是标准的编码格式。
    2,multipart/form-data: 窗体数据被编码为一条消息,页上的每个控件对应消息中的一个部分,这个一般文件上传时用。
    3,text/plain: 窗体数据以纯文本形式进行编码,其中不含任何控件或格式字符。

2、常用的编码方式
    form的enctype属性为编码方式,常用有两种:
        application/x-www-form-urlencoded(默认)
        multipart/form-data
    1.x-www-form-urlencoded
        浏览器用x-www-form-urlencoded的编码方式把form数据转换成一个字串(name1=value1&name2=value2…)
    2.multipart/form-data
        浏览器把form数据封装到http body中,然后发送到server。如果没有type=file的控件,用默认的application/x-www-form-urlencoded就可以了。但是如果type=file的话,就要用到multipart/form-data了。

十、Retrofit2及OkHttp3的区别

Retrofit2使用注解设置请求内容
Retrofit2回调主线程,OkHttp3回调子线程
Retrofit2可以做数据解析转换
Retrofit2可以使用在REST ful网络请求.

十一、Retrofit2源码分析(底层OkHttp3,注解了解,反射了解)

构建者构建
动态代理、反射
注解配置请求
底层基于OkHttpCall调用
上一篇 下一篇

猜你喜欢

热点阅读