Retrofit2使用教程

目录

案例下载传送门

主页

中文资料

用途

  • 效率非常高
  • 可以直接将结果转换成Java类
  • 结合RxJava使用简直起飞

注意

  • 使用Retrofit的前提是服务器端代码遵循REST规范 !!!
  • Retrofit requires at minimum Java 7 or Android 2.3.

基本概念

    常用注解:
            ####请求方法类,分别对应 HTTP 的请求方法;
            @Get / @POST / @PUT / @DELETE / @PATCH / @HEAD / @OPTIONS

    URL处理:
            @Path - 参数替换 - http://v.juhe.cn/group/10/users
            @GET("/group/{id}/users")
            public Call<List<User>> groupList(@Path("id") int groupId);

            @Query - 添加查询参数 - http://v.juhe.cn/group/10/users
            ?sort="传进来的sort"
            @GET("/group/{id}/users")
            public Call<List<User>> groupList(@Path("id") int groupId, @Query ("sort") String sort);

            @QueryMap - 多个查询参数,封装到Map中
            @GET("/group/{id}/users")
            public Call<List<User>> groupList(@QueryMap Map<String ,String > options);

使用步骤

1. 添加依赖
     1. 在com.android.tools.build:gradle 3.0 以上版本依赖在gradle 中的声明写法
         //Retrofit依赖包
         implementation 'com.squareup.retrofit2:retrofit:2.4.0'
         //添加数据解析依赖,大多数情况都是Json格式的解析,具体情况具体添加
         implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
         //可选项:如果依赖了okhttp包,那么Retrofit底层则会自动使用okhttp进行网络请求,效率会更快一点
         implementation 'com.squareup.okhttp3:okhttp:3.8.1'

     2. 在com.android.tools.build:gradle 3.0 以下版本依赖在gradle 中的声明写法
         例子:compile 'com.squareup.retrofit2:retrofit:2.4.0'
2. 创建数据模型
    AS中有GsonFormat插件可以帮助解析
    在线生成工具:https://www.bejson.com/json2javapojo/new/
3. 网络权限
    <!--添加网络权限-->
    <uses-permission android:name="android.permission.INTERNET" />
4. 创建REST API接口
    /**
     * 测试接口使用的是聚合数据提供的免费API,自行申请将KEY替换
     * 地址:https://www.juhe.cn/
     */
    public interface ApiService {
    //    用Retrofit需要后台接口遵循REST风格的请求
    //    请求示例:http://v.juhe.cn/weather/index?cityname=苏州&key=您申请的KEY
    //    基本地址(BASE_URL):http://v.juhe.cn
    //    功能地址(API):/weather/index
    //    请求参数(真正的参数):?cityname=苏州&key=您申请的KEY

        String BASE_URL = "http://v.juhe.cn";
        String KEY = "bc8a753f7********bedeb73ad18";

        /**
         * 接口1:获取天气信息, API一定是以 "/" 开头,这是Retrofit规范
         */
        @GET("/weather/index")
        Call<Weather> getWeather(@QueryMap Map<String, String> options);

    }
5. 构建Retrofit

    public class MainActivity extends AppCompatActivity implements View.OnClickListener{

        private Button btnRqt;
        private TextView tvMsg;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            tvMsg = findViewById(R.id.tv_msg);
            btnRqt = findViewById(R.id.btn_rqt);
            btnRqt.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.btn_rqt:
                    /**
                     * 构建Retrofit
                     */
                    Retrofit retrofit = new Retrofit.Builder()
                            .baseUrl(ApiService.BASE_URL)
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();
                    /**
                     * 构建接口实例
                     */
                    ApiService weatherAPI = retrofit.create(ApiService.class);
                    Map<String ,String > map = new HashMap();
                    map.put("cityname" , "北京");
                    map.put("key" , ApiService.KEY);
                    //返回的Call可以理解为是网络执行的对象
                    Call<Weather> call = weatherAPI.getWeather(map);
                    //同步执行请求
                    //call.execute();
                    //异步执行网络请求
                    call.enqueue(new Callback<Weather>() {
                        @Override
                        public void onResponse(Call<Weather> call, Response<Weather> response) {
                            Weather body = response.body();
                            tvMsg.setText(body.getResult().getToday().getDressing_advice());
                            tvMsg.setTextColor(getResources().getColor(R.color.colorPrimary));
                        }

                        @Override
                        public void onFailure(Call<Weather> call, Throwable t) {
                            tvMsg.setText(t.getMessage());
                            tvMsg.setTextColor(getResources().getColor(R.color.colorAccent));
                        }
                    });

                    break;
            }
        }
    }

案例下载传送门

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值