使用
使用可参考这篇文章:
http://blog.csdn.net/lmj623565791/article/details/51304204
1.1首先构建Retrofit对象,并制定API域名,数据返回格式(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可以添加一些参数配置,比如Interceptor。Retrofit有两种参数添加方式,一直是注解,另外一种是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);
}
}
这种方式可以作为公共的参数添加,比如Token。
1.2根据API新建一个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然后就是执行接口了
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转换器(Converter)和RxJava适配器(Adapter).
未完待续