定义拦截器类
public class AesEncryptInterceptor implements Interceptor {
private final String password;
public AesEncryptInterceptor(String password) {
this.password = password;
}
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
// 拿到请求参数
Request request = chain.request();
// 拿到请求 body
RequestBody body = request.body();
//对请求进行加密
if (body != null) {
Buffer buffer = new Buffer();
body.writeTo(buffer);
//将body 转成字符串,然后进行加密
String bodyString = buffer.readString(StandardCharsets.UTF_8);
String encryptString = AESHelper.encrypt(bodyString, password);
//重新构造请求
RequestBody newBody = RequestBody.create(encryptString, body.contentType());
request = request.newBuilder()
.post(newBody)
.build();
}
//对响应进行解密
try (Response response = chain.proceed(request)) {
ResponseBody responseBody = response.body();
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE);
Buffer buffer = source.getBuffer();
String responseBodyString = buffer.readString(StandardCharsets.UTF_8).replace("\"","");
String decryptString = AESHelper.decrypt(responseBodyString, password);
ResponseBody newResponseBody = ResponseBody.create(decryptString, responseBody.contentType());
return response.newBuilder().body(newResponseBody).build();
}
}
}
添加拦截器并使用 json/text 都可以
JSONObject requestBody = new JSONObject();
requestBody.put("user", "github suzhelan");
OkHttpClient client = new OkHttpClient().newBuilder()
.addInterceptor(new AesEncryptInterceptor("F621AA19C7A5F139F315853F40A7E24F"))
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(requestBody.toString(), mediaType);
Request request = new Request.Builder()
.url("http://localhost:8083/user/login")
.method("POST", body)
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
response.close();