Retrofit 基本使用

Retrofit

RetrofitSquare开源的网络框架,可以和Rxjava结合 使用,封装了Okhttp简化网络请求操作。

  1. Retrofit
  2. GitHub

Retrofit 使用

  • 依赖导入
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
//当前最新版
    //其他依赖 使用时将版本号与Retrofit对其即可
    Gson: com.squareup.retrofit2:converter-gson
    Jackson: com.squareup.retrofit2:converter-jackson
    Moshi: com.squareup.retrofit2:converter-moshi
    Protobuf: com.squareup.retrofit2:converter-protobuf
    Wire: com.squareup.retrofit2:converter-wire
    Simple XML: com.squareup.retrofit2:converter-simplexml
    Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

    以上导入的内容主要使用在Retrofit支持的解析数据方面
如支持String类型

        Retrofit retrofit = new Retrofit.Builder()      .addConverterFactory(ScalarsConverterFactory.create()).buid();

//Rxjava 交互
compile 'com.squareup.retrofit2:adapter-rxjava:xxxx'

retrofit = new Retrofit.Builder().addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();

@POST("Test")
    Observable<String> getLog();
  • 使用

假设我们有这样的请求

    http://www.user.com/users/USERNAME/code;

其中USERNAME是可变参数,我们就这样写接口

public interface SomeService {  
    @GET("/users/{user}/code")
    Call<String> someEndpoint(@Path("user") String userName);
}

这里出现了两个注解@GET@Path,@GET故名思意这是GET请求与之对应的@POSTPOST请求,而后面括号内的内容表示将字符串拼接到传入的url后面,而@Path表示将标记的参数拼接至指定位置及{user},而CallRetrofit中重要的一个概念,代表被封装成单个请求/响应的交互行为。

创建Retrofit

    Retrofit retrofit = new Retrofit.Builder()
     .addConverterFactory(ScalarsConverterFactory.create()) // 支持解析String
                .baseUrl("http://www.user.com")//网址
                .build();

        SomeService some = retrofit.create(SomeService.class);//创建接口实体
        Call<String> call = some.someEndpoint("MyName");//传入参数返回Call对象

进行网络请求:

//异步请求
   call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                textView.setText("成功+\n"+response.body().toString());
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                textView.setText("失败");
            }
        });
        //每个Call实例只能使用一次所以
        Call<String> call1 = call.clone();
        try {
        //同步请求
            Response<String> execute = call1.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
posted @ 2017-05-02 11:08  天涯海角路  阅读(159)  评论(0)    收藏  举报