我有从服务器返回的JSON有效负载,但是已加密。
让我们说改装电话看起来像这样:
@GET("/user/{id}/userprofile")
void listUserProfile(@Path("id") int id, Callback<UserProfile> cb);
那么我如何告诉改造首先解密有效载荷然后使用gson将json转换为POJO(在本例中为UserProfile对象)?我正在使用okHttp进行http客户端。
答案 0 :(得分:8)
可能为您的OkHttp客户端编写一个应用程序Interceptor
,它将解密正文:
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;
}
}
如果你没有使用OkHttp,我会优雅地删除答案。