Retrofit,Okhttp对每个Request统一动态添加header和参数

Retrofit,Okhttp对每个Request统一动态添加header和参数,第1张

原文: https://blog.csdn.net/sk719887916/article/details/52189602

添加统一通用header, 不会覆盖前面的header

okHttpClient.interceptors().add(new Interceptor() {

    @Override

    public Response intercept(Interceptor.Chain chain) throws IOException {

        Request original = chain.request()

        // Request customization: add request headers

        Request.Builder requestBuilder = original.newBuilder()

                    .addHeader("header-key", "value1")

                    .addHeader("header-key", "value2")

        Request request = requestBuilder.build()

        return chain.proceed(request)

    }

})

添加统一通用header, 会覆盖前面的header

okHttpClient.interceptors().add(new Interceptor() {

    @Override

    public Response intercept(Interceptor.Chain chain) throws IOException {

        Request original = chain.request()

        // Request customization: add request headers

        Request.Builder requestBuilder = original.newBuilder()

                .header("headerkey", "header-value")// <-- this is the important line

        Request request = requestBuilder.build()

        return chain.proceed(request)

    }

})

统一添加参数

OkHttpClient.Builder httpClient =

    new OkHttpClient.Builder()

httpClient.addInterceptor(new Interceptor() { 

    @Override

    public Response intercept(Chain chain) throws IOException {

        Request original = chain.request()

        HttpUrl originalHttpUrl = original.url()

        HttpUrl url = originalHttpUrl.newBuilder()

                .addQueryParameter("apikey", "your-actual-api-key")

                .build()

        // Request customization: add request headers

        Request.Builder requestBuilder = original.newBuilder()

                .url(url)

        Request request = requestBuilder.build()

        return chain.proceed(request)

    }

})

关于OKHTTP拦截器Interceptor很强大,很好用。因为公司有个需求需要对所有请求接口添加共有参数并且对共有参数进行签名。在OKHTTP中GET的请求参数和POST表单形式的参数很容易获取,但是对于BODY类型的一时没想到解决办法,后来想了想发现其实都是可以做的。

GET方法直接url.request().query()即可获得key=value&key=value形式的参数,可以直接拼凑参数,然后签名。

POST方法:有三种情况,表单,body,multipart三种情况,对于multipart主要是文件,一般过滤掉。

重要源码:

if (requestBody instanceof FormBody) {for (int i =0i <((FormBody) requestBody).size()i++) {rootMap.put(((FormBody) requestBody).encodedName(i), ((FormBody) requestBody).encodedValue(i))}} else {//buffer流Buffer buffer = new Buffer()requestBody.writeTo(buffer)String oldParamsJson = buffer.readUtf8()rootMap = mGson.fromJson(oldParamsJson, HashMap.class) //原始参数rootMap.put("publicParams", commomParamsMap) //重新组装String newJsonParams = mGson.toJson(rootMap) //装换成json字符串request = request.newBuilder().post(RequestBody.create(JSON, newJsonParams)).build()}

具体靠参考:http://blog.csdn.net/wuyinlei/article/details/57087872


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11449700.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-16
下一篇 2023-05-16

发表评论

登录后才能评论

评论列表(0条)

保存