Retrofit的使用
- 定义
Retrofit可以通过接口方法注解的方式完成Http请求。 - 实现方法
第一步:定义一个接口,接口中包含请求的方法,通过使用注解,将请求进行描述。
第二步:通过Retrofit.Builder完成Retrofit对象的实例化。
第三步:通过Retrofit对象的create方法传入接口的方式,完成接口的实例化。
第四步:通过接口对象调用相应的方法,完成网络的请求。 - 示例
第一步:
public interface ServerApi{
@GET("/square/okhttp/master/README.md")
Call<ResponseBody> getOkHttpReadMeMessage();
}
第二步:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://raw.github.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
第三步:
ServerApi serverApi = retrofit.create(ServerApi.class);
第四步:
serverApi.getOkHttpReadMeMessage().enqueue(new retrofit2.Callback<ResponseBody>() {
@Override
public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
}
@Override
public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
}
});
};
Important Notice:
1)addConverterFactory(Converter.Factory factory)
2)addCallAdapterFactory(CallAdapter.Factory factory)
注意上述示例的返回类型:Call,这是默认情况下的返回结果,Call是Retofit的请求和响应的类型,ResponseBody代表成功请求后的响应体。
比较常用的转换如下:
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create());
These are called call adapters, and Retrofit includes a few first-party modules for popular frameworks:
RxJava Observable & Single - com.squareup.retrofit2:adapter-rxjava
Guava ListenableFuture - com.squareup.retrofit2:adapter-guava
Java 8 CompleteableFuture - com.squareup.retrofit2:adapter-java8
Various third-party adapters have been created by the community for other libraries:
Bolts
Agera
These are called converters, and Retrofit includes a few first-party modules for popular frameworks:
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 Framework - com.squareup.retrofit2:converter-simpleframework
Scalars - com.squareup.retrofit2:converter-scalars
Various third-party converters have been created by the community for other libraries and serialization formats:
LoganSquare - com.github.aurae.retrofit2:converter-logansquare
FastJson - org.ligboy.retrofit2:converter-fastjson or org.ligboy.retrofit2:converter-fastjson-android
3)baseUrl(String baseUrl)中的baseUrl+endpoint的组合规则,注意加粗部分
BaseUrl: http://example.com/api/
EndPoint: foot/bar/
Result : http://example.com/api/foot/bar/
BaseUrl:http://example.com/api/
EndPoint: /foot/bar/
Result : http://example.com/foot/bar/
BaseUrl: http://example.com/
EndPoint:/foot/bar
Result:http://example.com/foot/bar
BaseUrl:http://example.com/
EndPoint:https://github.com/suqare/retrofit/
Result:https://github.com/suqare/retrofit/
BaseUrl:**http://**example.com
EndPoint://github.com/square/retrofit/
Result:http://github.com/square/retrofit/