一、基本使用
1、創(chuàng)建Retrofit類
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseHttpUrl.BASE_URL)
//使用網(wǎng)絡(luò)請求內(nèi)核,默認(rèn)就是okhttp??梢栽O(shè)置okhttp相關(guān)內(nèi)容
.client(new OkHttpClient())
//轉(zhuǎn)換器,作用就是講response的數(shù)據(jù)進(jìn)行解碼
.addConverterFactory(GsonConverterFactory.create())
//添加異步適配器,默認(rèn)使用ExecutorCallbackCall()。
// 默認(rèn)適配器實際上就是通過調(diào)用okhttp的call.enqueue()方法發(fā)起請求,并異步處理回調(diào)。
// 也可以使用rxjava進(jìn)行處理。后續(xù)文章中我們在說rxjava的使用。
//.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
2、自定義OkHttpClient()
// 1、創(chuàng)建http日志 攔截器
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Logger.e("okhttp",message);
}
});
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// 2、指定緩存路徑,緩存大小100Mb
Cache cache = new Cache(new File(StoragePathConfig.getAppCacheDir(), "HttpCache"),
1024 * 1024 * 100);
// 3、創(chuàng)建OkHttpClient
mOkHttpClient = new OkHttpClient.Builder()
//添加緩存
.cache(cache)
//添加自定義Intercept,可以統(tǒng)一設(shè)置Request的通用Header頭
.addInterceptor(new SignInterceptor())//添加簽名
//添加http日志攔截器
.addInterceptor(httpLoggingInterceptor)
//默認(rèn)重試連接1次,如果需要多次重試。需要自定義intercept
.retryOnConnectionFailure(true)
//重試intercept ,最大重試10次
.addInterceptor(new RetryInterceptor(10))
//設(shè)置超時時間
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
/**
* 自定義的,重試N次的攔截器
* 通過:addInterceptor 設(shè)置
*/
public static class RetryInterceptor implements Interceptor {
public int maxRetry;//最大重試次數(shù)
private int retryNum = 0;//假如設(shè)置為3次重試的話,則最大可能請求4次(默認(rèn)1次+3次重試)
public RetryInterceptor(int maxRetry) {
this.maxRetry = maxRetry;
}
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
Log.i("Retry","num:"+retryNum);
while (!response.isSuccessful() && retryNum < maxRetry) {
retryNum++;
Log.i("Retry","num:"+retryNum);
response = chain.proceed(request);
}
return response;
}
}
3、創(chuàng)建請求接口interface
public interface RetrofitApiImpl{
@Headers({
"Cache-Control: max-age=640000",
"User-Agent: Retrofit-Sample-App"
})
@POST("audit/home/get-home")
Call<TestVo> getHome(@Body HashMap<String,String> map);
//表單形式上傳
@FormUrlEncoded
@POST("loanmall/activity/get-list")
Call<TestVo> getHome1(@Field("first_name") String first,@Field("second_name") String second);
//上傳文件類型
@Multipart
@PUT("common/image/post-upload")
Call<TestVo> updatePhoto(@Part("file\"; filename=hahaha\"") RequestBody photo,@Part("dir") String dir,@Part("rule") String rule);
@POST("common/image/post-upload")
Call<TestVo> updatePhoto1(@Body MultipartBody multipartBody);
}
4、發(fā)起請求
4.1 發(fā)起普通post
//創(chuàng)建請求類
RetrofitApiImpl retrofitApi = retrofit.create(RetrofitApiImpl.class);
//調(diào)用接口
Call<TestVo> call = retrofitApi.getHome(new HashMap<String, String>());
//發(fā)起請求
call.enqueue(new Callback<TestVo>() {
@Override
public void onResponse(Call<TestVo> call, Response<TestVo> response) {
}
@Override
public void onFailure(Call<TestVo> call, Throwable t) {
}
});
4.2 發(fā)起file類型文件
RetrofitApiImpl retrofitApi = retrofit.create(RetrofitApiImpl.class);
//創(chuàng)建multpart類型
MultipartBody.Builder builder = new MultipartBody.Builder();
RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
builder.addFormDataPart("file", file.getName(), requestBody);
builder.addFormDataPart("dir", "user");
int width = AbDisplayUtil.dip2px(70);
builder.addFormDataPart("rule", width+"x"+width+"_c");
builder.setType(MultipartBody.FORM);
MultipartBody multipartBody = builder.build();
//發(fā)起請求
Call<TestVo> call = retrofitApi.updatePhoto1(multipartBody);
call.enqueue(new Callback<TestVo>() {
@Override
public void onResponse(Call<TestVo> call, Response<TestVo> response) {
}
@Override
public void onFailure(Call<TestVo> call, Throwable t) {
}
});