详细的Retrofit 2.0 使用教程(含实例讲解)

开发资料

最近接触到了Retrofit相关的知识,通过学习,对Retrofit框架的使用有了一定的理解,通过查找资料,我认为下面这一篇文章总结的很好,贴上文章链接。

这是一份很详细的 Retrofit 2.0 使用教程(含实例讲解)

上面这一篇文章可以作为Retrofit手册使用了,感谢原作者。另外,我参考了另外两篇文章:

  1. Retrofit的简单使用(入门篇)-GET请求
  2. Android 网络请求库Retrofit简单使用

结合以上两篇文章,吸取其中的优点,并替换不再支持的url调用,自己动手写了一个demo,现在奉上,以备不时之需能尽快上手。下面是快速使用Retrofit的步骤:

快速上手DEMO

  • 步骤说明

步骤1:添加Retrofit库的依赖 
步骤2:创建 接收服务器返回数据 的类 
步骤3:创建 用于描述网络请求 的接口 
步骤4:创建 Retrofit 实例 
步骤5:创建 网络请求接口实例 并 配置网络请求参数 
步骤6:发送网络请求(采用最常用的异步方式)

封装了 数据转换、线程切换的操作

步骤7: 处理服务器返回的数据

接下来,我们一步步进行讲解。

demo中使用的URL为 http://112.124.22.238:8081/course_api/wares/hot?pageSize=28&curPage=1

准备工作

配置依赖

compile 'com.squareup.okhttp3:okhttp:3.7.0'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'

创建 接收服务器返回数据的类

package com.xzy.retrofitdemo;

import java.util.List;

/**
 * Function:根据返回的json格式构造的bean
 * Created by xuzhuyun on 2018/1/15.
 */

public class ShopBean {

    /**
     * {
     * "currentPage": 1,
     * "list": [
     * {
     * "id": 1,
     * "imgUrl": "http://7mno4h.com2.z0.glb.qiniucdn.com/s_recommend_55c1e8f7N4b99de71.jpg",
     * "name": "联想(Lenovo)拯救者14.0英寸游戏本(i7-4720HQ 4G 1T硬盘 GTX960M 2G独显 FHD IPS屏 背光键盘)黑",
     * "price": 5979.0,
     * "sale": 8654
     * }
     * ],
     * "pageSize": 1,
     * "totalCount": 28,
     * "totalPage": 28
     * }
     **/

    private int currentPage;
    private int pageSize;
    private int totalPage;
    private int totalCount;

    private List<ListBean> list;


    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public List<ListBean> getList() {
        return list;
    }

    public void setList(List<ListBean> list) {
        this.list = list;
    }

    /**
     * id : 1
     * name : 联想(Lenovo)拯救者14.0英寸游戏本(i7-4720HQ 4G 1T硬盘 GTX960M 2G独显 FHD IPS屏 背光键盘)黑
     * imgUrl : http://7mno4h.com2.z0.glb.qiniucdn.com/s_recommend_55c1e8f7N4b99de71.jpg
     * description : null
     * price : 5979.0
     * sale : 8654
     */
    public static class ListBean {
        private int id;
        private String imgUrl;
        private String name;
        private double price;
        private Object description;
        private int sale;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getImgUrl() {
            return imgUrl;
        }

        public void setImgUrl(String imgUrl) {
            this.imgUrl = imgUrl;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public double getPrice() {
            return price;
        }

        public void setPrice(double price) {
            this.price = price;
        }

        public Object getDescription() {
            return description;
        }

        public void setDescription(Object description) {
            this.description = description;
        }

        public int getSale() {
            return sale;
        }

        public void setSale(int sale) {
            this.sale = sale;
        }

        @Override
        public String toString() {
            return "ListBean{" +
                    "id=" + id +
                    ", imgUrl='" + imgUrl + '\'' +
                    ", name='" + name + '\'' +
                    ", price=" + price +
                    ", description=" + description +
                    ", sale=" + sale +
                    '}';
        }
    }

    @Override
    public String toString() {
        return "ShopBean{" +
                "currentPage=" + currentPage +
                ", pageSize=" + pageSize +
                ", totalPage=" + totalPage +
                ", totalCount=" + totalCount +
                ", list.get(0)=" + list.get(0).toString() +
                '}';
    }
}

创建 用于描述网络请求 的接口 

package com.xzy.retrofitdemo.service;

import com.xzy.retrofitdemo.ShopBean;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

/**
 * Function:访问api的接口
 * Created by xuzhuyun on 2018/1/15.
 */

public interface ShopService {
    @GET("/course_api/wares/hot")
    Call<ShopBean> getShop(@Query("pageSize") int pageSize, @Query("curPage") int curPage);
}

创建 Retrofit 实例(网络接口服务的包装类)

package com.xzy.retrofitdemo;

import android.content.Context;

import com.xzy.retrofitdemo.constant.Constant;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retrofit 网络接口服务的包装类
 * Created by xuzhuyun on 2018/1/15.
 */
public class RetrofitWrapper {
    private static RetrofitWrapper instance;
    private Context mContext;
    private Retrofit retrofit;

    private RetrofitWrapper() {
        //1.创建Retrofit对象
        retrofit = new Retrofit.Builder().baseUrl(Constant.BASEURL) // 定义访问的主机地址
                .addConverterFactory(GsonConverterFactory.create())  //解析方法
                .build();
    }


    /**
     * 单例模式
     *
     * @return
     */
    public static RetrofitWrapper getInstance() {
        if (instance == null) {
            synchronized (RetrofitWrapper.class) {
                if (instance == null) {
                    instance = new RetrofitWrapper();
                }
            }
        }
        return instance;
    }


    public <T> T create(final Class<T> service) {
        return retrofit.create(service);
    }
}

定义访问Model

网络服务的包装类定义好了之后,在定义一个访问的Model
package com.xzy.retrofitdemo.model;

import android.content.Context;

import com.xzy.retrofitdemo.Param;
import com.xzy.retrofitdemo.RetrofitWrapper;
import com.xzy.retrofitdemo.ShopBean;
import com.xzy.retrofitdemo.service.ShopService;

import retrofit2.Call;

/**
 * Function:构建访问的model
 * Created by xuzhuyun on 2018/1/15.
 */

public class ShopBeanModel {
    private static ShopBeanModel famousInfoModel;
    private ShopService mFamousService;

    /**
     * 单例模式
     *
     * @return
     */
    public static ShopBeanModel getInstance(Context context) {
        if (famousInfoModel == null) {
            famousInfoModel = new ShopBeanModel(context.getApplicationContext());
        }
        return famousInfoModel;
    }


    private ShopBeanModel(Context context) {
        mFamousService = (ShopService) RetrofitWrapper.getInstance().create(ShopService.class);
    }

    /**
     * 查询接口
     *
     * @return
     */
    public Call<ShopBean> queryLookUp(Param param) {
        Call<ShopBean> infoCall = mFamousService.getShop((int) param.getArg1(), (int) param.getArg2());
        return infoCall;
    }
}
上面对Retrofit和访问model使用了单例模式,进行了封装,接口都写完了,下面是调用。

如何使用

构建好接口以后,可以使用了!

使用分为四步:

  • 创建Retrofit对象
  • 创建访问API的请求
  • 发送请求
  • 处理结果 
    主要代码如下:
ShopBeanModel shopBeanModel = ShopBeanModel.getInstance(this);
        //创建访问的API请求
        Param param = new Param();
        //构建请求参数实体
        //pageSize = 10,curPage=1
        param.setArg1(10);
        param.setArg2(1);
        Call<ShopBean> callFamous = shopBeanModel.queryLookUp(param);
        callFamous.enqueue(new Callback<ShopBean>() {
            @Override
            public void onResponse(Call<ShopBean> call, Response<ShopBean> response) {
                ShopBean result = response.body();
                if (result != null) {
                    Log.i(TAG, "onResponse2: " + result.toString());
                }
            }

            @Override
            public void onFailure(Call<ShopBean> call, Throwable t) {
                Log.i(TAG, "onFailure: " + t.getMessage());
            }
        });
如果没有进行封装,则调用代码是这样的:
 Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASEURL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ShopService service = retrofit.create(ShopService.class);
        //pageSize = 10,curPage=1
        Call<ShopBean> callShops = service.getShop(10, 1);

        callShops.enqueue(new Callback<ShopBean>() {
            @Override
            public void onResponse(Call<ShopBean> call, Response<ShopBean> response) {
                if (response.isSuccessful()) {
                    ShopBean result = response.body();
                    Log.i(TAG, "onResponse1: " + result.toString());

                }
            }

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

            }
        });

DEMO下载












猜你喜欢

转载自blog.csdn.net/jdfkldjlkjdl/article/details/79072983