android–OkHttp如何记录请求体

android–OkHttp如何记录请求体,第1张

概述我正在使用一个拦截器,我想记录我正在制作的请求的正文,但我看不到这样做的任何方法.可能吗?publicclassLoggingInterceptorimplementsInterceptor{@OverridepublicResponseintercept(Chainchain)throwsIOException{Requestrequest=chain.requ

我正在使用一个拦截器,我想记录我正在制作的请求的正文,但我看不到这样做的任何方法.

可能吗 ?

public class LoggingInterceptor implements Interceptor {    @OverrIDe    public Response intercept(Chain chain) throws IOException {        Request request = chain.request();        long t1 = System.nanoTime();        Response response = chain.proceed(request);        long t2 = System.nanoTime();        double time = (t2 - t1) / 1e6d;        if (request.method().equals("GET")) {            Logs.info(String.format("GET " + F_REQUEST_WITHOUT_BODY + F_RESPONSE_WITH_BODY, request.url(), time, request.headers(), response.code(), response.headers(), response.body().charStream()));        } else if (request.method().equals("POST")) {            Logs.info(String.format("POST " + F_REQUEST_WITH_BODY + F_RESPONSE_WITH_BODY, request.url(), time, request.headers(), request.body(), response.code(), response.headers(), response.body().charStream()));        } else if (request.method().equals("PUT")) {            Logs.info(String.format("PUT " + F_REQUEST_WITH_BODY + F_RESPONSE_WITH_BODY, request.url(), time, request.headers(), request.body().toString(), response.code(), response.headers(), response.body().charStream()));        } else if (request.method().equals("DELETE")) {            Logs.info(String.format("DELETE " + F_REQUEST_WITHOUT_BODY + F_RESPONSE_WITHOUT_BODY, request.url(), time, request.headers(), response.code(), response.headers()));        }        return response;    }}

结果:

POST  [some url] in 88,7ms    Zonename: touraine    Source: AndroID    body: retrofit.clIEnt.OkClIEnt@1df53f05 <-request.body().toString() gives me this, but I would like the content string    Response: 500    Date: Tue, 24 Feb 2015 10:14:22 GMT    body: [some content] 

解决方法:

尼古拉的回答对我不起作用.我的猜测是ByteString#toString()的实现发生了变化.这个解决方案对我有用:

private static String bodyToString(final Request request){    try {        final Request copy = request.newBuilder().build();        final Buffer buffer = new Buffer();        copy.body().writeto(buffer);        return buffer.readUtf8();    } catch (final IOException e) {        return "dID not work";    }}

从readUtf8()的文档:

Removes all bytes from this, decodes them as UTF-8, and returns the string.

这应该是你想要的.

总结

以上是内存溢出为你收集整理的android – OkHttp如何记录请求体全部内容,希望文章能够帮你解决android – OkHttp如何记录请求体所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

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

原文地址:https://54852.com/web/1100634.html

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

发表评论

登录后才能评论

评论列表(0条)

    保存