在OkHttp库中使用Interceptor

时间:2015-01-24 10:57:50

标签: java retrofit okhttp interceptor

我需要使用所有请求参数生成签名验证:

  • 查询
  • 方法
  • 安全令牌

所以,我写了一个小的SignatureInterceptor类:

public class SignatureInterceptor implements Interceptor {

    private String token;
    private String signature = "";
    private String method;
    private String query;

    public SignatureInterceptor() {
            this.token = "456456456456";
    }

    @Override
    public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
            return chain.proceed(originalRequest);
        }

        method = originalRequest.method();
        query = originalRequest.urlString();

        Request authenticatedRequest = originalRequest.newBuilder()
                .method(originalRequest.method(), authenticate(originalRequest.body()))
                .addHeader("signature", signature)
                .build();
        return chain.proceed(authenticatedRequest);
    }

    private RequestBody authenticate(final RequestBody body) {
        return new RequestBody() {
            @Override
            public MediaType contentType() {
                return body.contentType();
            }

            @Override
            public long contentLength() throws IOException {
                return -1;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                BufferedSink authSink = Okio.buffer(sink);
                body.writeTo(sink);

                String data = authSink.buffer().readUtf8();
                signature = generateSignature(method, query, data, token);
                authSink.close();
            }
        };
    }
}

问题是,对于intercetors,结果在执行期间流式传输,因此在处理之前我无法获得签名值。

那么,有没有一种聪明的方法可以在头文件中插入writeTo()流方法中生成的签名值?

根据@Jesse的回答

更新代码。

private class SignatureInterceptor implements Interceptor {

    @Override
    public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        String data = "";
        if (originalRequest.body() != null) {
            BufferedSink authSink = new Buffer();
            originalRequest.body().writeTo(authSink);
            data = authSink.buffer().readUtf8();
            authSink.close();
        }
        Request authenticatedRequest = originalRequest.newBuilder()
                .addHeader(HEADER_SIGNATURE, buildSignature(data))
                .build();
        return chain.proceed(authenticatedRequest);
    }
}

1 个答案:

答案 0 :(得分:5)

您无需创建自己的RequestBody类;只有当你改变身体时才有必要。

writeTo方法的内容移至intercept,以便在调用proceed之前计算签名。使用该签名添加标题。