在OkHttp库中使用Interceptor

Bib*_*ibu 2 java interceptor retrofit okhttp

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

  • 询问
  • 方法
  • 身体
  • 安全令牌

所以,我写了一个小的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();
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,对于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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Jes*_*son 5

您不需要创建自己的RequestBody类; 只有当你改变身体时才需要这个.

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