Retrofit2+RxJava 簡單使用

yugoal發表於2018-09-05

##前言 學習Retrofit2+RxJava時間不長,大概知道怎麼用。根據需求簡單的封裝一下。

1.介面

public interface GankIO{
	@GET("App/10/{index}")
	Call<AndroidBean> getApp(@Path("index") String index);
}
複製程式碼

@POST 請求方式
("819-1") URL地址
@QueryMap Map<String,String> cityId 請求引數 ResponseBody 返回資料

2.網路請求類#

public class HttpManager {

	public final static int CONNECT_TIMEOUT =5;
	public final static int READ_TIMEOUT=5;
	public final static int WRITE_TIMEOUT=5;
	//伺服器地址
	private static final String BASE_URL = "";
	private static Retrofit retrofit;

	private static Retrofit getRetrofit() {
    	if (retrofit == null) {
        	//網路快取路徑檔案
        	// File httpCacheDirectory = new File(BaseApplication.getInstance().getExternalCacheDir(), "responses");
        	//通過攔截器設定快取,暫未實現
        	//CacheInterceptor cacheInterceptor = new CacheInterceptor();

        	OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                .addInterceptor(new MyInterceptors())
                .build();

        	retrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
    	}
    	return retrofit;
	}
}
複製程式碼

3.攔截器 MyInterceptors#

public class MyInterceptors implements Interceptor {
    private static final String TAG = "MyInterceptors";
    @Override
    public Response intercept(Chain chain) throws IOException {

        //封裝headers
        Request request = chain.request().newBuilder()
                .addHeader("model","24037") //手機型號
                .build();
        Headers headers = request.headers();
        //列印
        System.out.println("phoneModel is : " + headers.get("phoneModel"));
        String requestUrl = request.url().toString(); //獲取請求url地址
        String methodStr = request.method(); //獲取請求方式
        RequestBody body = request.body(); //獲取請求body
        String bodyStr = (body==null?"":body.toString());
        //列印Request資料
        Log.d(TAG, "intercept: Request Url is :" + requestUrl + "\nMethod is : " + methodStr + "\nRequest Body is :" + bodyStr + "\n");

        Response response = chain.proceed(request);

        if (response != null) {
            //byte[] str = Base64.decode(response.body().string(), Base64.DEFAULT);
//            s1 = Base64Decoder.decode(response.body().string());
            //s1 = new String(str);
        } else {
            System.out.println("Respong is null");
        }
        Log.d(TAG, "intercept: response  "+response.body().toString());
        return response;
    }
}
複製程式碼

4.呼叫

Api.getRetrofit().create(GankIO.class).getApp(index).enqueue(new Callback<AndroidBean>() {
        @Override
        public void onResponse(Call<AndroidBean> call, Response<AndroidBean> response) {
          //請求成功處理
        }

        @Override
        public void onFailure(Call<AndroidBean> call, Throwable t) {
           //請求失敗處理
        }
    });複製程式碼