如何处理 JSON 负载的解密
How to handle decryption of JSON payload
我有一个 JSON 负载从服务器返回,但它已加密。
假设改造调用如下所示:
@GET("/user/{id}/userprofile")
void listUserProfile(@Path("id") int id, Callback<UserProfile> cb);
那么我如何告诉改造首先解密有效负载,然后使用 gson 将 json 转换为 POJO(在本例中为 UserProfile 对象)?我正在为 http 客户端使用 okHttp。
可能为您的 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,我会优雅地删除答案。
我有一个 JSON 负载从服务器返回,但它已加密。
假设改造调用如下所示:
@GET("/user/{id}/userprofile")
void listUserProfile(@Path("id") int id, Callback<UserProfile> cb);
那么我如何告诉改造首先解密有效负载,然后使用 gson 将 json 转换为 POJO(在本例中为 UserProfile 对象)?我正在为 http 客户端使用 okHttp。
可能为您的 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,我会优雅地删除答案。