我正在使用Retrofit 2.0

我想加密我的@body示例用户对象

@POST("users/new")
Call<User> createUser(@Body User newUser);

然后解密响应。

最好的方法是什么?

最佳答案

使用Interceptor加密主体。

public class EncryptionInterceptor implements Interceptor {

    private static final String TAG = EncryptionInterceptor.class.getSimpleName();
    private static final boolean DEBUG = true;

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        RequestBody oldBody = request.body();
        Buffer buffer = new Buffer();
        oldBody.writeTo(buffer);
        String strOldBody = buffer.readUtf8();

        MediaType mediaType = MediaType.parse("text/plain; charset=utf-8");
        String strNewBody = encrypt(strOldBody);
        RequestBody body = RequestBody.create(mediaType, strNewBody);
        request = request.newBuilder().header("Content-Type", body.contentType().toString()).header("Content-Length", String.valueOf(body.contentLength())).method(request.method(), body).build();

        return chain.proceed(request);
    }

    private static String encrypt(String text) {
        //your code
    }
}

然后将Interceptor添加到Retrofit中:
client = new OkHttpClient.Builder().addNetworkInterceptor(new EncryptionInterceptor()).build();
retrofit = new Retrofit.Builder().client(client).build();

有关Interceptor的更多信息:https://github.com/square/okhttp/wiki/Interceptors

关于Android Retrofit AES加密/解密POST和响应,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36327439/

10-09 09:24