I am using Retrofit 2.0
I want to encrypt my @body example the User Object
@POST("users/new")
Call<User> createUser(@Body User newUser);
and then decrypt the response .
what is the best way to do it ?
Use Interceptors to encrypt the body.
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
    }
}
Then add the Interceptor to the Retrofit:
client = new OkHttpClient.Builder().addNetworkInterceptor(new EncryptionInterceptor()).build();
retrofit = new Retrofit.Builder().client(client).build();
More about Interceptors: https://github.com/square/okhttp/wiki/Interceptors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With