Android - 如何在Retrofit中检查2个请求是否相同?

时间:2017-12-01 05:57:23

标签: android retrofit retrofit2 okhttp

我已经使用他们的哈希码检查了请求是否相同。

final Request original = chain.request();
MyLog.log(original.hashCode());

然而,它们是不同的:

  

245712287 144127529

当我尝试创建一个扩展okhttp3.Request的类时,我收到了一个错误:

  

无法继承最终' okhttp3.Request'

还有其他方法可以检查请求是否相同吗?

1 个答案:

答案 0 :(得分:0)

创建的辅助类,它返回Request hashcode

public class RetrofitUtil {

    public static long hashcode(Request request){

        String url = request.url().url().toString();
        String body = getRequestBodyAsString(request.body());

        long result = url != null ? url.hashCode() : 0;
        result = 31 * result + body != null ? body.hashCode() : 0;
        return result;

    }

    public static String getRequestBodyAsString(final RequestBody requestBody) {
        try {
            final RequestBody copy = requestBody;
            final Buffer buffer = new Buffer();
            if (copy != null)
                copy.writeTo(buffer);
            String requestBodyAsString = java.net.URLDecoder.decode(buffer.readUtf8(), "UTF-8");
            return requestBodyAsString;
        } catch (final IOException e) {
        }
        return "";
    }

}