Retrofit2概述

Retrofit2

1.Retrofit2概述

1,Retrofit框架是Square公司出品的网络框架.
运用注解和动态代理.
底层是使用OKHttp封装的。
准确来说,网络请求的工作本质上是OkHttp完成,而 Retrofit 仅负责网络请求接口的封装。

2.Retrofit2的好处

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

3.Retrofit2配置

1,官网:http://square.github.io/retrofit/
2,依赖:
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
3,OkHttp库依赖
由于Retrofit是基于OkHttp,所以还需要添加OkHttp库依赖
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
4,添加网络权限
<uses-permission android:name="android.permission.INTERNET" />

4,Retrofit2的使用步骤

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

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

1.Retrofit2发送GET

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

//接口服务
public interface MyServer {
    
    //GET
    @GET("categories?appKey=908ca46881994ffaa6ca20b31755b675")
    Call<ResponseBody> getData1();

    @GET("categories?")
    Call<ResponseBody> getData2(@Query("appKey") String appkey);

    @GET("categories?")
    Call<ResponseBody> getData3(@QueryMap Map<String,Object> map);
}

//Get异步
private void initGetEnqueue() {

    //1.创建Retrofit对象
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(MyServer.URL)
            .build();
    
    //2.获取MyServer接口服务对象
    MyServer myServer = retrofit.create(MyServer.class);
    
    //3.获取Call对象
    //方式一
    Call<ResponseBody> call1 = myServer.getData1();

    //方式二
    Call<ResponseBody> call2 = myServer.getData2("908ca46881994ffaa6ca20b31755b675");

    //方式三
    Map<String,Object> map = new HashMap<>();
    map.put("appKey","908ca46881994ffaa6ca20b31755b675");
    Call<ResponseBody> call = myServer.getData3(map);

    //4.Call对象执行请求
    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());
        }
    });
}


//GET同步
private void initGetExecute() {

    //1.创建Retrofit对象
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(MyServer.URL)
            .build();

    //2.获取MyServer接口服务对象
    MyServer myServer = retrofit.create(MyServer.class);

    //3.获取Call对象
    final Call<ResponseBody> call = myServer.getData1();

    new Thread(){//子线程执行
        @Override
        public void run() {
            super.run();

            try {
                //4.Call对象执行请求
                Response<ResponseBody> response = call.execute();

                final String result = response.body().string();

                Log.e("retrofit", "onResponse: "+result);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText(result);//默认直接回调主线程
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.start();

}

2.Retrofit2发送POST

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

public interface MyServer {
    
    //POST("categories?")    POST("categories")相同
    @POST("categories?")
    @FormUrlEncoded
    Call<ResponseBody> postData1(@Field("appKey") String appKey);

    @POST("categories")  
    @FormUrlEncoded
    Call<ResponseBody> postData2(@FieldMap Map<String,Object> map);
}

//POST异步
private void initPostEnqueue() {

    //1.创建Retrofit对象
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(MyServer.URL)
            .build();

    //2.获取MyServer接口服务对象
    MyServer myServer = retrofit.create(MyServer.class);

    //3.获取Call对象
    //方式一
    Call<ResponseBody> call1 = myServer.postData1("908ca46881994ffaa6ca20b31755b675");

    //方式二
    Map<String,Object> map = new HashMap<>();
    map.put("appKey","908ca46881994ffaa6ca20b31755b675");
    Call<ResponseBody> call = myServer.postData2(map);

    //4.Call对象执行请求
    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());
        }
    });
}

7.Retrofit注解

注解代码 请求格式

请求方式:
@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(自定义参数)

8.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());
        }
    });
}

9.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());
        }
    });
}

10.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了。

9.Retrofit2及OkHttp3的区别

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

10.Retrofit2源码分析(底层OkHttp3,注解了解,反射了解)

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,670评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,928评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,926评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,238评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,112评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,138评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,545评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,232评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,496评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,596评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,369评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,226评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,600评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,906评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,185评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,516评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,721评论 2 335

推荐阅读更多精彩内容

  • 前言 如果看Retrofit的源码会发现其实质上就是对okHttp的封装,使用面向接口的方式进行网络请求,利用动态...
    李某人吖阅读 2,005评论 0 0
  • 概述 随着Google对HttpClient 摒弃,和Volley的逐渐没落,OkHttp开始异军突起,而Retr...
    SnowDragonYY阅读 876评论 0 1
  • 概述 随着Google对HttpClient 摒弃,和Volley的逐渐没落,OkHttp开始异军突起,而Retr...
    BoBoMEe阅读 80,290评论 13 144
  • 1、需要的安装包 nginx:http://nginx.org/en/download.html;php:php-...
    _歌者阅读 1,223评论 1 0
  • 弱者易怒。朋友圈刷屏。的确如此。 我,就是一个易怒的弱者。 小时候易怒的记忆还很清晰。小学时,常常被周围的男同学弄...
    littlecolor阅读 848评论 0 51