美文网首页程序员
Retrofit个人总结

Retrofit个人总结

作者: huangandroid | 来源:发表于2017-12-03 18:06 被阅读29次

    记录一下开发中使用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;
    
        }
    }
    

    相关文章

      网友评论

        本文标题:Retrofit个人总结

        本文链接:https://www.haomeiwen.com/subject/lhczbxtx.html