我正在使用Retrofit 2.0
我想加密我的@body示例用户对象
[self createBackButton];
然后解密响应。
最好的方法是什么?
答案 0 :(得分:4)
实际上你可以使用拦截器来加密你的身体。
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 = CodeMachine.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 ){
//your code
}
}
为您的改装添加拦截器:
client = new OkHttpClient.Builder().addNetworkInterceptor(new EncryptionInterceptor()).build();
retrofit = new Retrofit.Builder().client(client).build();
有关拦截器的更多信息:https://github.com/square/okhttp/wiki/Interceptors