How to handle decoding of JSON payload

I have a JSON payload returned from the server but encrypted.

Suppose a modification request is as follows:

@GET("/user/{id}/userprofile")  
void listUserProfile(@Path("id") int id, Callback<UserProfile> cb);  

So, how can I say to modify, to first decrypt the payload, and then use gson to convert json to POJO (in this case, the UserProfile object)? I am using okHttp for the http client.

+4
source share
1 answer

Perhaps an application Interceptorfor your OkHttp client that decrypts the body will do the trick:

public class DecryptedPayloadInterceptor implements Interceptor {

    private final DecryptionStrategy mDecryptionStrategy;

    public interface DecryptionStrategy {
        String decrypt(InputStream stream);
    }

    public DecryptedPayloadInterceptor(DecryptionStrategy mDecryptionStrategy) {
        this.mDecryptionStrategy = mDecryptionStrategy;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Response response = chain.proceed(chain.request());
        if (response.isSuccessful()) {
            Response.Builder newResponse = response.newBuilder();
            String contentType = response.header("Content-Type");
            if (TextUtils.isEmpty(contentType)) contentType = "application/json";
            InputStream cryptedStream = response.body().byteStream();
            String decrypted = null;
            if (mDecryptionStrategy != null) {
                decrypted = mDecryptionStrategy.decrypt(cryptedStream);
            } else {
                throw new IllegalArgumentException("No decryption strategy!");
            }
            newResponse.body(ResponseBody.create(MediaType.parse(contentType), decrypted));
            return newResponse.build();
        }
        return response;
    }
}

If you are not using OkHttp, I will gracefully delete the answer.

+6
source

Source: https://habr.com/ru/post/1608060/


All Articles