Retrofit2.0 增加公共参数
16lz
2021-01-26
有时候,我们会在请求里面加一些公共的参数,比如下面的"device=android",Retrofit2.0应该怎么做呢?
http://192.168.31.3:90/wallet/info?device=android
我们可以使用Interceptor,Interceptor给我们的印象是可以拦截信息,但它也是可以改造请求然后再发出去。而且Interceptor还可以添加多个呢。
OkHttpClient.Builder builder = new OkHttpClient.Builder().addInterceptor(new ChuckInterceptor(context)).addInterceptor(loggingInterceptor).addInterceptor(httpBaseParamsLoggingInterceptor).readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);//设置连接超时时间
我们直接封装一个httpBaseParamsLoggingInterceptor,它实现Interceptor的接口就可以了
import android.util.Log;import com.siluyun.module.common.utils.Utils;import java.io.EOFException;import java.io.IOException;import java.nio.charset.Charset;import java.nio.charset.UnsupportedCharsetException;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.concurrent.TimeUnit;import okhttp3.Connection;import okhttp3.FormBody;import okhttp3.Headers;import okhttp3.HttpUrl;import okhttp3.Interceptor;import okhttp3.MediaType;import okhttp3.Protocol;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response;import okhttp3.ResponseBody;import okhttp3.internal.http.HttpHeaders;import okhttp3.internal.platform.Platform;import okhttp3.logging.HttpLoggingInterceptor;import okio.Buffer;import okio.BufferedSource;import static okhttp3.internal.platform.Platform.INFO;public class HttpBaseParamsLoggingInterceptor implements Interceptor { Map queryParamsMap = new HashMap<>(); Map paramsMap = new HashMap<>(); Map headerParamsMap = new HashMap<>(); List headerLinesList = new ArrayList<>(); private HttpBaseParamsLoggingInterceptor() { } @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Request.Builder requestBuilder = request.newBuilder(); // process header params inject Headers.Builder headerBuilder = request.headers().newBuilder(); if (headerParamsMap.size() > 0) { Iterator iterator = headerParamsMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); headerBuilder.add((String) entry.getKey(), (String) entry.getValue()); } } if (headerLinesList.size() > 0) { for (String line: headerLinesList) { headerBuilder.add(line); } } requestBuilder.headers(headerBuilder.build()); // process header params end // process queryParams inject whatever it's GET or POST if (queryParamsMap.size() > 0) { injectParamsIntoUrl(request, requestBuilder, queryParamsMap); } // process header params end // process post body inject if (request.method().equals("POST") && request.body().contentType().subtype().equals("x-www-form-urlencoded")) { FormBody.Builder formBodyBuilder = new FormBody.Builder(); if (paramsMap.size() > 0) { Iterator iterator = paramsMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); formBodyBuilder.add((String) entry.getKey(), (String) entry.getValue()); } } RequestBody formBody = formBodyBuilder.build(); String postBodyString = bodyToString(request.body()); postBodyString += ((postBodyString.length() > 0) ? "&" : "") + bodyToString(formBody); requestBuilder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"), postBodyString)); } else { // can't inject into body, then inject into url injectParamsIntoUrl(request, requestBuilder, paramsMap); } request = requestBuilder.build(); return chain.proceed(request); } // func to inject params into url private void injectParamsIntoUrl(Request request, Request.Builder requestBuilder, Map paramsMap) { HttpUrl.Builder httpUrlBuilder = request.url().newBuilder(); if (paramsMap.size() > 0) { Iterator iterator = paramsMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); httpUrlBuilder.addQueryParameter((String) entry.getKey(), (String) entry.getValue()); } } requestBuilder.url(httpUrlBuilder.build()); } private static String bodyToString(final RequestBody request){ try { final RequestBody copy = request; final Buffer buffer = new Buffer(); if(copy != null) copy.writeTo(buffer); else return ""; return buffer.readUtf8(); } catch (final IOException e) { return "did not work"; } } public static class Builder { HttpBaseParamsLoggingInterceptor interceptor; public Builder() { interceptor = new HttpBaseParamsLoggingInterceptor(); } public Builder addParam(String key, String value) { interceptor.paramsMap.put(key, value); return this; } public Builder addParamsMap(Map paramsMap) { interceptor.paramsMap.putAll(paramsMap); return this; } public Builder addHeaderParam(String key, String value) { interceptor.headerParamsMap.put(key, value); return this; } public Builder addHeaderParamsMap(Map headerParamsMap) { interceptor.headerParamsMap.putAll(headerParamsMap); return this; } public Builder addHeaderLine(String headerLine) { int index = headerLine.indexOf(":"); if (index == -1) { throw new IllegalArgumentException("Unexpected header: " + headerLine); } interceptor.headerLinesList.add(headerLine); return this; } public Builder addHeaderLinesList(List headerLinesList) { for (String headerLine: headerLinesList) { int index = headerLine.indexOf(":"); if (index == -1) { throw new IllegalArgumentException("Unexpected header: " + headerLine); } interceptor.headerLinesList.add(headerLine); } return this; } public Builder addQueryParam(String key, String value) { interceptor.queryParamsMap.put(key, value); return this; } public Builder addQueryParamsMap(Map queryParamsMap) { interceptor.queryParamsMap.putAll(queryParamsMap); return this; } public HttpBaseParamsLoggingInterceptor build() { return interceptor; } }}
怎么使用呢?非常简单:
HttpBaseParamsLoggingInterceptor httpBaseParamsLoggingInterceptor = new HttpBaseParamsLoggingInterceptor .Builder() .addParam("device", "android").build();
参考
- Retrofit2.0 公共参数(固定参数)
更多相关文章
- Android(安卓)ListView中动态显示和隐藏Header&Footer的方法
- Android(安卓)- SharedPreferences共享数据的相同Context
- Android:通过build gradle中的buildTypes设置自动log开关(二)
- Android版本适配(基于 6.0 ~ 9.0)
- Android调用系统相册和相机选择图片并显示在imageview中
- Android动态换肤(一、应用内置多套皮肤)
- [置顶] android下调试声卡驱动之wm8960介绍一
- 海豚浏览器推出Android(安卓)7.0版,支持跨平台同步书签、设置等
- Android中合多图片和文字合成PDF文件---路很长