Retrofit2 的基本使用 (一)

概述

    Android开发中我们常用的基本网络请求方式有OkHttp,HttpClient, HttpUrlConnection这三个都是基于http请求封装的一个网络请求客户端。
    Retrofit2是由Square公司开发的一个网络请求调度框架,对OkHttp进行了外层封装,方便我们使用。

    本文主要介绍内容:

             - 基本的GET/POST请求的使用
             - Gson与Converter

一 . 基本的GET/POST请求的使用

使用到的公共API
http://www.tngou.net/api/cook/list
http://www.tngou.net/api/top/list

1.要想使用Retrofit2框架,首先需要导包

Retrofit2的包:
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
GSON解析的包
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'

2.定义请求接口

public interface IRetrofitService {
/**
 * 通过注解来设置请求方式(GET请求),括号里面参数是请求的子目录({category} ,相当于一个占位符)
 * @Path("category")String category 该参数用来填补{category}
 * @Query("id") int id ,@Query("page") int page,@Query("rows") int rows :GET请求参数,会自动按照Http协议格式添加到url上
 */
@GET("/api/{category}/list")
Call<Tngou> getList(@Path("category")String category,@Query("id") int id, @Query("page") int page, @Query("rows") int rows);

/**
 * POST请求
 * @FormUrlEncoded 该注解表示表单请求
 * @Field("id") int id  表单数据(自动安装格式添加到请求头上)
 */
@POST("/api/{category}/list")
@FormUrlEncoded
Call<Tngou> postList(@Path("category") String category, @Field("id") int id,@Field("page") int page,@Field("rows") int rows);

}

更多详细注解请参考:你真的会用Retrofit2吗?Retrofit2完全教程


3. 使用代码

        //1.创建Retrofit实例
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.tngou.net")// 设置baseUrl
                // 设置数据转换器(使用Gosn解析JSON数据)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

         // 2.返回自定义接口的代理对象(内部使用了java动态代理)
        IRetrofitService retrofitService = retrofit.create(IRetrofitService.class);

        //3.使用代理对象调用自己定义的请求方法,得到一个执行请求的对象
        Call<Tngou> call = retrofitService.getList("cook",0, 1, 10);
        Call<Tngou> callPost = retrofitService.postList("cook",0, 1, 10);

        //4.使用该请求对象发起异步或同步请求
       call.enqueue(new Callback<Tngou>() {// 发起异步请求
            // 请求成功,返回请求结果(在主线程,可以直接操作控件)
            @Override
            public void onResponse(Call<Tngou> call, Response<Tngou> response) {
                adapter.addDatas(response.body().getTngou());
            }
            // 请求失败
            @Override
            public void onFailure(Call<Tngou> call, Throwable t) {
                t.printStackTrace();// 输出失败信息
            }
        });
       // callPost.enqueue(this);

4.什么是Converter

默认情况Retrofit只是将请求回来的数据转换为ResponseBody,而Converter就是Retrofit为我们提供用于将ResponseBody转换为我们想要的类型的一个转换器。结合GSON使用,提供了一个GsonConverter,我们只需要提供一个GSON解析需要使用的对象,就可以自动为我们解析GSON数据了。

GSON使用教程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值