OkHttp 添加拦截器 实现优雅加解密拦截器

定义拦截器类

    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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值