本文主要是介绍Retrofit2 添加header和baseparam,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一.添加header
1.请求拦截器:
方式一:OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(new Interceptor() { @Overridepublic Response intercept(Interceptor.Chain chain) throws IOException {Request original = chain.request();Request request = original.newBuilder().header("User-Agent", "Your-App-Name").header("Accept", "application/vnd.yourapi.v1.full+json").method(original.method(), original.body()).build();return chain.proceed(request);}}方式二:OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(new Interceptor() { @Overridepublic Response intercept(Interceptor.Chain chain) throws IOException {Request original = chain.request();Request request = original.newBuilder().addHeader("Cache-Control", "no-cache").addHeader("Cache-Control", "no-cache").method(original.method(), original.body()).build();return chain.proceed(request);}}OkHttpClient client = httpClient.build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(API_BASE_URL).addConverterFactory(GsonConverterFactory.create()).client(client).build();
OkHtt请求头通过拦截器添加Header,两种方式的不同.header(key, val):如果key相同,最后一个val会将前面的val值覆盖.addHeader(key, val):如果key相同,最后一个val不会将前面的val值覆盖,而是新添加一个Header
2.动态添加
@GET("get.php")Call<StoryResponse> getPhp(@Header("headerType") String type);
@GET("get.php")Call<StoryResponse> getPhp(@HeaderMap Map<String,String> type);
3.静态添加
@Headers("headertype:2")@GET("get.php")Call<StoryResponse> getPhp();
@Headers({"headertype:2","type:3"})@GET("get.php")Call<StoryResponse> getPhp();
二 .添加baseParam
为所有的网络请求添加公用的param,如uid,imei等,仍然使用到了拦截器:
//base节点拦截器Interceptor baseParamInterceptor = new Interceptor() {@Overridepublic Response intercept(Chain chain) throws IOException {Request original = chain.request();HttpUrl originalUrl = original.url();HttpUrl url = originalUrl.newBuilder().addQueryParameter("apikey","1234").addQueryParameter("imei","1456").build();Request.Builder requestBuilder = original.newBuilder().url(url);Request request = requestBuilder.build();return chain.proceed(request);}};
然后添加拦截器就可以了:
//定制OkHttpOkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();//OkHttp进行添加拦截器loggingInterceptorhttpClientBuilder..addInterceptor(headerInterceptor);return httpClientBuilder.build();
这篇关于Retrofit2 添加header和baseparam的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!