如對(duì)Retrofit的使用還不太了解,請(qǐng)查閱我的上篇文章Retrofit的基本了解和簡(jiǎn)單使用
簡(jiǎn)介:本篇主要介紹Retrofit接口注解的使用以及Retrofit配合Okhttp實(shí)現(xiàn)網(wǎng)絡(luò)響應(yīng)錯(cuò)誤攔截和自定義錯(cuò)誤攔截
部分依賴:
compile 'com.jakewharton.rxbinding:rxbinding:0.4.0'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
1.創(chuàng)建回調(diào)接口:
interface GithubAPIInterface {
@GET("users/{username}")
Call<GithubUserDetail> requestUserDetails(@Path("username") String username);
@GET("users")
Call<List<GithubUser>> requestUsers(@Query("per_page") Integer perPage);
}
備注:
* @GET 指定請(qǐng)求方式,
* @Query 表示請(qǐng)求參數(shù),將會(huì)以key=value的方式拼接在url后面
* 如requestUsers:完整地址https://api.github.com/users?per_page=1
* @PATH 拼接
* 如:requestUserDetails
* https://api.github.com/users/mojombo
*/
2.初始化Retrofit實(shí)例設(shè)置攔截器:
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.i("Rxjava", message);
}
});
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.retryOnConnectionFailure(true)//設(shè)置重連
.connectTimeout(15, TimeUnit.SECONDS)
.addNetworkInterceptor(httpLoggingInterceptor)
.build();
備注:
* HttpLoggingInterceptor可以設(shè)置無(wú)參,這里L(fēng)ogger()設(shè)置定向過(guò)濾Rxjava,默認(rèn)是okhttp
* 設(shè)置攔截范圍:BODY--- 請(qǐng)求/響應(yīng)行 + 頭 + 體
* 攔截器分為兩種:addInterceptor:設(shè)置應(yīng)用攔截器,主要用于設(shè)置公共參數(shù),頭信息,日志攔截等addNetworkInterceptor:設(shè)置網(wǎng)絡(luò)攔截器,主要用于重試或重寫
*/
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ENDPOINT)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
mGithubAPI = retrofit.create(GithubAPIInterface.class);
備注:
* 1.基地址必須有(可以是全部,也可以是部分)
* 2.添加攔截器(非必須)
* 3.Converter是對(duì)于Call<T>中T的轉(zhuǎn)換, Call<ResponseBody>--------->Call<Poju>
* Call<T>中的Call也是可以被替換的,而返回值的類型就決定你后續(xù)的處理程序邏輯(非必須)
* 4.初始化Retrofit
* 5.用Retrofit創(chuàng)建出接口的代理對(duì)象,用代理對(duì)象來(lái)操作其方法,返回Call<Poju>
* 通過(guò)Call<Poju>來(lái)請(qǐng)求入隊(duì),execute/enqueue(同步/異步)
*
*/
3.請(qǐng)求回調(diào)獲取數(shù)據(jù)
call = mGithubAPI.requestUsers(PER_PAGE);
call.enqueue(new Callback<List<GithubUser>>() {
@Override
public void onResponse(Call<List<GithubUser>> call, Response<List<GithubUser>> response) {
final List<GithubUserDetail> githubUserDetails = new ArrayList<>();
if (response.isSuccessful()) {
final List<GithubUser> githubUsers = response.body();
for (GithubUser user : githubUsers) {
mService.requestUserDetails(user.mLogin).enqueue(new Callback<GithubUserDetail>() {
@Override
public void onResponse(Call<GithubUserDetail> call, Response<GithubUserDetail> response) {
GithubUserDetail githubUserDetail = response.body();
githubUserDetails.add(githubUserDetail);
if (githubUserDetails.size() == 1) {
EventBus.getDefault().post(githubUserDetails);
}
}
@Override
public void onFailure(Call<GithubUserDetail> call, Throwable t) {
}
});
}
}
}
@Override
public void onFailure(Call<List<GithubUser>> call, Throwable t) {
// ErrorHandler.handle(t);//自定義錯(cuò)誤攔截
}
});
4.根據(jù)服務(wù)端接口返回自定義錯(cuò)誤攔截:
public class BodyResponse<T> {
public String code;
public String message;
public T data;
@Override
public String toString() {
return "BodyResponse{" +
"code='" + code + '\'' +
", message='" + message + '\'' +
", data=" + data +
'}';
}
}
public class ErrorHandler {
public static BodyResponse handle(Throwable throwable) {
if (throwable instanceof HttpException) {
HttpException error = (HttpException) throwable;
try {
return new Gson().fromJson(error.response().errorBody().string(),
BodyResponse.class);
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.i("tag","throwable.printStackTrac--------------------");
throwable.printStackTrace();
}
return null;
}
}