Retrofit簡單使用

使用

使用可參考這篇文章:
http://blog.csdn.net/lmj623565791/article/details/51304204

1.1首先構(gòu)建Retrofit對象,并制定API域名,數(shù)據(jù)返回格式(GSON):

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(new CustomInterceptor())
        .build();
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.douban.com/v2/")
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build();

OkhttpClient可以添加一些參數(shù)配置,比如Interceptor。Retrofit有兩種參數(shù)添加方式,一直是注解,另外一種是Interceptor,比如:

public class CustomInterceptor implements Interceptor {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        HttpUrl httpUrl = request.url().newBuilder()
                .addQueryParameter("token", "tokenValue")
                .build();
        request = request.newBuilder().url(httpUrl).build();
        return chain.proceed(request);
    }
}

這種方式可以作為公共的參數(shù)添加,比如Token。

1.2根據(jù)API新建一個(gè)Java接口,用注解方式來描述,比如:

public interface BlueService {
    @GET("book/search")
    Call<String> getSearchBooks(@Query("a") String name,
                                @Query("b") int age);
    @GET("book/search")
    Call<String> getSearchBooks(@QueryMap Map<String, String> options);
    @GET("book/{id}")
    Call<String> getBook(@Path("id") String id,
                         @QueryMap Map<String, String> options);
    @FormUrlEncoded//不能用于get請求
    @POST("book/reviews")
    Call<String> addReviews(@Field("book") String bookId,
                            //encoded中文和特殊字符是否編碼
                            @Field(value = "title", encoded = true) String title);
    @FormUrlEncoded
    @POST("book/reviews")
    Call<String> addReviews(@FieldMap Map<String, String> fields);}

1.2然后就是執(zhí)行接口了

Call<String> call = mBlueService.getSearchBooks("小王子", 20);
call.enqueue(new Callback<String>() {
    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        Loger.e("" + response.body());
    }
    @Override
    public void onFailure(Call<String> call, Throwable t) {
    }
});

使用的話還有更多功能,比如文件上傳,使用Gson轉(zhuǎn)換器(Converter)RxJava適配器(Adapter).

未完待續(xù)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容