如何处理JSON有效负载的解密

j2e*_*nue 6 encryption android json retrofit

我有一个从服务器返回的JSON有效负载,但它是加密的.

让我们说改装电话看起来像这样:

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

那么我怎么能告诉改造首先解密有效载荷然后使用gson将json转换为POJO(在这种情况下是UserProfile对象)?我正在使用okHttp进行http客户端.

Nik*_*ski 9

可能Interceptor为你的OkHttp客户端编写一个解密身体的应用程序就可以了:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你没有使用OkHttp,我会优雅地删除答案.