Retrofit网络库使用及解析

来源:互联网 发布:郑州学历网络教育 编辑:程序博客网 时间:2024/05/22 12:40

Retrofit网络库使用及解析

简介

Retrofit是目前最火的网络请求库,Retrofit与okhttp共同出自于Square公司,retrofit就是对okhttp做了一层封装。把网络请求都交给了Okhttp,我们只需要通过简单的配置就能使用retrofit来进行网络请求。

使用

官方文档
http://square.github.io/retrofit/

Github地址
https://github.com/square/retrofit

第一步:

Grandle中引入Retrofit依赖

compile ‘com.squareup.retrofit2:retrofit:2.1.0’

compile ‘com.squareup.retrofit2:converter-gson:2.1.0’

第二步:

创建Retrofit对象

Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.pgyer.com/")                .addConverterFactory(GsonConverterFactory.create())                .client(new OkHttpClient()).build();

第三步:

创建请求接口及请求数据实体类

public interface ViewGroupService {    @GET("apiv1?userId={userId}")    Call<UserInfo> getUserInfo(@Path("userId") String userId);    @POST("apiv1/app/viewGroup")    Call<ViewGroupData> getViewGroupData(@FieldMap Map<String,String> map);}
public class UserInfo{    private String username;    private String address;    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }}
public class ViewGroupData {    private String code;    private String message;    private List<AppInfo> data;    public String getCode() {        return code;    }    public void setCode(String code) {        this.code = code;    }    public String getMessage() {        return message;    }    public void setMessage(String message) {        this.message = message;    }    public List<AppInfo> getData() {        return data;    }    public void setData(List<AppInfo> data) {        this.data = data;    }}

解释:

Call对象:An invocation of a Retrofit method that sends a request to a webserver and returns a response

@Path:替换参数

@FieldMap:post参数

第四步:

请求数据

get请求

ViewGroupService service = retrofit.create(ViewGroupService.class);Call<UserInfo> call = service.getUserInfo("111111");UserInfo userInfo = call.execute();

post请求

Map<String,String> map = new HashMap<>();map.put(“aId”,“9aa0a936dd2653f96ee4511acf3d3afb”);map.put(“_api_key”,“5b21ee35f5f87245f4feeb4456177ae6”);ViewGroupService viewGroupService = retrofit.create(ViewGroupService.class);Call<ViewGroupData> call = viewGroupService.getViewGroupData(map);        call.enqueue(new Callback<ViewGroupData>() {            @Override            public void onResponse(Call<ViewGroupData> call, Response<ViewGroupData> response) {                try {                    ViewGroupData viewGroupData = response.body();                }catch (Exception e){                    e.printStackTrace();                }            }            @Override            public void onFailure(Call<ViewGroupData> call, Throwable t) {            }        });

原理

Retrofit就是充当了一个适配器(Adapter)的角色:将一个Java接口翻译成一个Http请求,然后用OkHttp去发送这个请求

Volley是HTTP请求是需要创建一个Request对象,然后把这个请求对象放到一个队列中,在网络线程中用HttpUrlConnection去请求

Retrofit是使用Java的动态代理,create方法就是返回了一个Proxy.newProxyInstance动态代理对象

什么是动态代理

Java动态代理就是调用某个Class的方法前或后,插入你想要执行的代码,比如你在买入前判断是否绑卡

源码分析

1、一个retrofit2.http包,里面全部是定义HTTP请求的Java注解,比如GET、POST、PUT、DELETE、Headers、Path、Query等等

2、余下的retrofit2包中几个类和接口就是全部retrofit的代码了,代码真的很少,很简单,因为retrofit把网络请求这部分功能全部交给了OkHttp了

对外接口

Retrofit的设计非常插件化而且轻量级,真的是非常高内聚而且低耦合,这个和它的接口设计有关。Retrofit中定义了4个接口:

Callback

这个接口就是retrofit请求数据返回的接口,只有两个方法

void onResponse(Response<T> response);void onFailure(Throwable t);

Converter

这个接口主要的作用就是将HTTP返回的数据解析成Java对象,主要有Xml、Gson、protobuf等等,你可以在创建Retrofit对象时添加你需要使用的Converter实现(看上面创建Retrofit对象的代码)

Call

这个接口主要的作用就是发送一个HTTP请求,Retrofit默认的实现是OkHttpCall,你可以根据实际情况实现你自己的Call类,这个设计和Volley的HttpStack接口设计的思想非常相似,子类可以实现基于HttpClient或HttpUrlConnetction的HTTP请求工具,这种设计非常的插件化,而且灵活

CallAdapter

上面说到过,CallAdapter中属性只有responseType一个,还有一个 T adapt(Call call)方法,这个接口的实现类也只有一个,DefaultCallAdapter。这个方法的主要作用就是将Call对象转换成另一个对象,可能是为了支持RxJava才设计这个类的吧

0 0
原创粉丝点击