Retrofit配置及各情况处理

Retrofit配置及各情况处理,第1张

1、Retrofit创建

2、Retrofit实现Cookie自动化管理

3、Retrofit,Gson解析,请求返回的类型不统一,假如double返回的是null

4、请求参数日志打印

5、统一请求参数添加到请求头中

6、统一请求参数添加到请求body中

7、缓存的拦截

8、BaseUrl动态切换

9、拦截指定接口,动态更改返回值便于测试

点击传送查看

点击传送查看

1.第一种办法,依赖第三方库

配置信息如下

2.第二种办法,拦截器拦截(个人推荐第二种,可控性高)

给大家推荐一个打印日志库,很漂亮的日志结构

然后在httpClientBuilder中添加拦截

然后在httpClientBuilder中添加拦截

然后在httpClientBuilder中添加拦截

然后在httpClientBuilder中添加拦截

用了一个博客中民间大神的拦截动态替换baseUrl方法有点问题,我暂时用了一种简单粗暴方法

上边的路径是我随便写的,post中写全路径,这个优先级最高,同时设置了baseUrl不受影响

给大家一个专门写动态替换baseUrl连接 传送门

有时候我们需要返回指定值测试,可能需要空或者null等,迫于无法修改服务器返回数据,也没必要让后台修改数据,所以引发一个问题,如果拦截返回内容并修改指定字段值

然后在httpClientBuilder中添加拦截

retrofit是使用okhttp3,做为网络请求,okhttp3有个Interceptor接口,可以对请求和响应进行拦截。通过这个机制,我们可以设计自己的一套日志拦截器,打印一些必要的信息。

自定义拦截器

首先要自己定义一个拦截器类,并实现Interceptor接口,在里面打印一些信息,如下LogInterceptor.java类。

public class LogInterceptor implements Interceptor{

    public static final String TAG = "LogInterceptor.java"

    @Override

    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request()

        //the request url

        String url = request.url().toString()

        //the request method

        String method = request.method()

        long t1 = System.nanoTime()

        HLog.d(TAG,String.format(Locale.getDefault(),"Sending %s request [url = %s]",method,url))

        //the request body

        RequestBody requestBody = request.body()

        if(requestBody!= null) {

            StringBuilder sb = new StringBuilder("Request Body [")

            okio.Buffer buffer = new okio.Buffer()

            requestBody.writeTo(buffer)

            Charset charset = Charset.forName("UTF-8")

            MediaType contentType = requestBody.contentType()

            if (contentType != null) {

                charset = contentType.charset(charset)

            }

            if(isPlaintext(buffer)){

                sb.append(buffer.readString(charset))

                sb.append(" (Content-Type = ").append(contentType.toString()).append(",")

                        .append(requestBody.contentLength()).append("-byte body)")

            }else {

                sb.append(" (Content-Type = ").append(contentType.toString())

                        .append(",binary ").append(requestBody.contentLength()).append("-byte body omitted)")

            }

            sb.append("]")

            HLog.d(TAG, String.format(Locale.getDefault(), "%s %s", method, sb.toString()))

        }

        Response response = chain.proceed(request)

        long t2 = System.nanoTime()

        //the response time

        HLog.d(TAG,String.format(Locale.getDefault(),"Received response for [url = %s] in %.1fms",url, (t2-t1)/1e6d))

        //the response state

        HLog.d(TAG,String.format(Locale.CHINA,"Received response is %s ,message[%s],code[%d]",response.isSuccessful()?"success":"fail",response.message(),response.code()))

        //the response data

        ResponseBody body = response.body()

        BufferedSource source = body.source()

        source.request(Long.MAX_VALUE) // Buffer the entire body.

        Buffer buffer = source.buffer()

        Charset charset = Charset.defaultCharset()

        MediaType contentType = body.contentType()

        if (contentType != null) {

            charset = contentType.charset(charset)

        }

        String bodyString = buffer.clone().readString(charset)

        HLog.d(TAG,String.format("Received response json string [%s]",bodyString))

        return response

    }

    static boolean isPlaintext(Buffer buffer){

        try {

            Buffer prefix = new Buffer()

            long byteCount = buffer.size() < 64 ? buffer.size() : 64

            buffer.copyTo(prefix, 0, byteCount)

            for (int i = 0 i < 16 i++) {

                if (prefix.exhausted()) {

                    break

                }

                int codePoint = prefix.readUtf8CodePoint()

                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {

                    return false

                }

            }

            return true

        } catch (EOFException e) {

            return false // Truncated UTF-8 sequence.

        }

    }

}


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

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

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

发表评论

登录后才能评论

评论列表(0条)

保存