Retrofit個人總結

weixin_34128411發表於2017-12-03

記錄一下開發中使用retrofit的時候的一些總結筆記。

@Url適合用於比如BaseUrl不一樣的情況。@Url後面就是url全路徑

@GET
Observable<AppPathBean> getThreeAppUrl(@Url String path);

@Path適合於路徑中某個欄位不一樣。

  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);

也可以加請求引數 實際請求路徑就是:group/{id}/users/?sort=sort

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);

如果不確定引數的具體長度,那麼可以使用@QueryMap

 @GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);

@Header適合與請求需要新增額外的header,或者需要修改公共中的請求頭資訊

@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)


@Headers("Cache-Control: max-age=640000")
@GET("widget/list")
Call<List<Widget>> widgetList();


@Headers({
    "Accept: application/vnd.github.v3.full+json",
    "User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call<User> getUser(@Path("username") String username);

我們在實際開發中一般請求頭中的引數是一定的,比如都需要在請求頭中新增token,但是還是還有有些介面中並不想要token,比如登入介面中請求頭引數可能就不一樣。但是一般我們都會在封裝OkHttp 的時候在請求頭中預設新增token,這個時候我們需要在攔截器中判斷是否新增token,比如Authorization 不為空,那麼我們不需要在請求頭中新增token.


import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by huangjie on 2017/9/7.
 */

public class HttpClientManager {

    private static HttpClientManager mInstance;
    private HttpInterface mInterface;
     //攔截器
    private static Interceptor CACHE_CONTROL_INTERCEPTER = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();

            //如果請求頭中 Authorization不為空或者Token為空
            if (original.header("Authorization") != null
                    || StringUtils.isEmpty(SharedPreferenceUtils.getToken())) {
                return chain.proceed(original);
            } else {
                Request.Builder requestBuilder = original.newBuilder()
                        .header("Authorization", "Bearer" + SharedPreferenceUtils.getToken())
                        .header("Content-Type", "application/json")
                        .method(original.method(), original.body());
                Request request = requestBuilder.build();
                LogUtils.error("請求ulr:" + request.url());
                return chain.proceed(request);
            }

        }
    };
     //快取檔案
    private static File cacheFile = new File(BaseApplication.getContext().getFilesDir(), "cache");
    static int cacheSize = 10 * 1024 * 1024;
    private static Cache mCache = new Cache(cacheFile, cacheSize);
    
    private static OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
            .addInterceptor(CACHE_CONTROL_INTERCEPTER)
            .cache(mCache)
            .connectTimeout(10, TimeUnit.SECONDS)
       .sslSocketFactory(SSLSocketFactoryUtil.createSSLSocketFactory(), new TrustAllManager())
            .build();


    public static HttpClientManager getInstance() {
        if (mInstance == null) {
            synchronized (HttpClientManager.class) {
                if (mInstance == null) {
                    mInstance = new HttpClientManager();
                }
            }
        }
        return mInstance;
    }


    public HttpInterface getClient() {
        if (mInterface == null) {
            mInterface = new Retrofit.Builder()
                    .baseUrl(Constants.BASE_URL)
                    .client(mOkHttpClient)
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
                    .create(HttpInterface.class);
        }
        return mInterface;

    }
}

相關文章