美文网首页
Retrofit 基本使用教程(一)

Retrofit 基本使用教程(一)

作者: 奋斗滴熊猫 | 来源:发表于2018-07-23 17:18 被阅读0次

    1.Retrofit介绍

    1.Retrofit 是Square公司基于RESTful风格推出的网络封装框架

    2.Retrofit是基于OKHttp的网络请求框架的二次封装,也就是说它的底层是基于OKHTTP  ,

    Retrofit本身并不是真正意义的网络请求框架  只是本身是基于网路请求二次封装的框架

    3.Retrofit优点:

    1.API设计简洁易用

    2.注解化配置高度解耦

    3.支持多种解析器、

    4.支持Rxjava

    2.Retrofit 使用

    1.添加依赖包:

    implementation 'com.squareup.retrofit2:retrofit:2.4.0'//Retrofit库                                     

    implementation 'com.squareup.okhttp3:okhttp:3.11.0'//okhttp库

    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'//数据解析器库

    2.添加网络请求权限

    3.创建接口设置请求类型和参数

    public interface MyInterface {

        @GET("userInfo/loginByPhone.do")

        Call login(@Query("phone") String phone, @Query("pwd") String pwd, @Query("type") int type, @Query("code") String code);

    }

    4.创建Retrofit对象 设置数据解析器

        //创建Retrofit 对象

        Retrofit retrofit = new Retrofit.Builder().baseUrl(ROOT_URL).addConverterFactory(GsonConverterFactory.create()).build();

    5.生成接口调用接口方法获取Call对象

    //获取接口对象

    MyInterface myInterface = retrofit.create(MyInterface.class);

    //

    Call call = myInterface.login("17051000000", "a12345678", 1, "");

    6.发送请求处理返回数据

    call.enqueue(new Callback() {

        @Override

        public void onResponse(Call call, Response response) {

            int code = response.code();

            System.out.println(code + "9999999");

            UserInfoBean body = response.body();

            String message = response.message();

            Log.e("MainActivity", "onResponse:message " + message);

            Log.e("MainActivity", "onResponse:body " + body.toString());

            Log.e("MainActivity", "onResponse:code " + code);

        }

        @Override

        public void onFailure(Call call, Throwable t) {

            String localizedMessage = t.getLocalizedMessage();

            String message = t.getMessage();

            Log.e("MainActivity", "onFailure: message" + message);

            Log.e("MainActivity", "onFailure: localizedMessage" + localizedMessage);

        }

    });

    原文链接

    http://note.youdao.com/noteshare?id=14835407bbe783172f7c2652b20c9b61&sub=66E3BA791EBF4222821670C24FEDB39F

    相关文章

      网友评论

          本文标题:Retrofit 基本使用教程(一)

          本文链接:https://www.haomeiwen.com/subject/sqbjmftx.html