如何从okhttp3.ResponseBody获取URL?

时间:2019-07-25 06:41:05

标签: java android kotlin retrofit2 okhttp3

我在项目中使用Retrofit 2。我需要处理解析错误并在出现错误的情况下记录请求URL。

我想在一个地方做所有事情。因此,我做了一个包装,以便在改造级别进行解析。

工厂:

TestApplicationRunner

转换器:

import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.lang.reflect.Type
import javax.inject.Inject

class LogGsonConverterFactory @Inject constructor(private val factory: GsonConverterFactory) : Converter.Factory() {

    override fun responseBodyConverter(
        type: Type,
        annotations: Array<out Annotation>,
        retrofit: Retrofit
    ): Converter<ResponseBody, *>? {
        val delegate: Converter<ResponseBody, *>? = factory.responseBodyConverter(type, annotations, retrofit)

        return LogResponseBodyConverter(delegate ?: return null)
    }

    override fun requestBodyConverter(
        type: Type, parameterAnnotations: Array<out Annotation>,
        methodAnnotations: Array<out Annotation>,
        retrofit: Retrofit
    ): Converter<*, RequestBody>? = factory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit)
}

通过反射我可以做到


import com.google.gson.JsonSyntaxException
import okhttp3.ResponseBody
import retrofit2.Converter

class LogResponseBodyConverter<T>(private val converter: Converter<ResponseBody, T>) : Converter<ResponseBody, T> {

    override fun convert(value: ResponseBody): T? {
        try {
            return converter.convert(value)
        } catch (parseException: JsonSyntaxException) {
            // Here I want to get URL and log an exception. But how to get url?
            throw parseException
        }
    }
}

或者使用我可以提供给解析器的拦截器

((Http1ExchangeCodec.ChunkedSource) ((Exchange.ResponseBodySource) ((RealBufferedSource) ((ForwardingSource) ((RealBufferedSource) ((ResponseBody.BomAwareReader) value.reader).source).source).delegate).source).delegate).url

是否有更正确的方法来获得所需的结果?

2 个答案:

答案 0 :(得分:0)

ZoomX — Android Logger Interceptor是一个很好的拦截器,可以帮助您解决问题。

答案 1 :(得分:0)

Object delegateObj = readField(value, "delegate");
Object sourceObj1 = readField(delegateObj, "source");
Object sourceObj2 = readField(sourceObj1, "source");
Object sourceObj3 = readField(sourceObj2, "source");
Object sourceObj4 = readField(sourceObj3, "source");
Object sourceObj5 = readField(sourceObj4, "source");
HttpUrl url = (HttpUrl) readField(sourceObj5, "url");



Object readField(Object obj, String fieldName) throws NoSuchFieldException, IllegalAccessException {
    Field f = obj.getClass().getDeclaredField(fieldName);
    f.setAccessible(true);
    return f.get(obj);
}
相关问题