Retrofit的使用

来源:互联网 发布:选择公理 知乎 编辑:程序博客网 时间:2024/06/05 08:21

Retrofit介绍

Retrofit是由Square公司出品的针对于Android和Java的类型安全的Http客户端,
如果看源码会发现其实质上就是对okHttp的封装,使用面向接口的方式进行网络请求,利用动态生成的代理类封装了网络接口请求的底层,
其将请求返回javaBean,对网络认证 REST API进行了很好对支持此,使用Retrofit将会极大的提高我们应用的网络体验。

Retrofit入门

public class Example01 {    public interface BlogService {        @GET("blog/{id}")            //这里的{id} 表示是一个变量//获取指定ID的Blog        Call<ResponseBody> getBlog(/** 这里的id表示的是上面的{id} */@Path("id") int id);    }    public static void main(String[] args) throws IOException {        //创建Retrofit实例//        创建Retrofit实例时需要通过Retrofit.Builder,并调用baseUrl方法设置URL。//        注: Retrofit2 的baseUlr 必须以 /(斜线) 结束,//        不然会抛出一个IllegalArgumentException,//                所以如果你看到别的教程没有以 / 结束,//        那么多半是直接从Retrofit 1.X 照搬过来的。        Retrofit retrofit = new Retrofit.Builder()                .baseUrl("http://localhost:4567/")                .build();//注意,这里是interface不是class,所以我们是无法直接调用该方法,// 我们需要用Retrofit创建一个BlogService的代理对象。        BlogService service = retrofit.create(BlogService.class);//       拿到代理对象之后,就可以调用该方法啦。        Call<ResponseBody> call = service.getBlog(2);        // 用法和OkHttp的call如出一辙        // 不同的是如果是Android系统回调方法执行在主线程        call.enqueue(new Callback<ResponseBody>() {            @Override            public void onResponse(                    Call<ResponseBody> call, Response<ResponseBody> response) {                try {                    System.out.println(response.body().string());                } catch (IOException e) {                    e.printStackTrace();                }            }            @Override            public void onFailure(Call<ResponseBody> call, Throwable t) {                t.printStackTrace();            }        });    }

1.1、创建Retrofit实例

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(“http://localhost:4567/“)
.build();

1.2、接口定义

以获取指定id的Blog为例:

public interface BlogService {
@GET(“blog/{id}”)
Call getBlog(@Path(“id”) int id);
}

1.3、接口调用

Call call = service.getBlog(2);
// 用法和OkHttp的call如出一辙,
// 不同的是如果是Android系统回调方法执行在主线程
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call call, Throwable t) {
t.printStackTrace();
}
});

0 0