当前位置:   article > 正文

拦截http请求打印入参出参(Okhttp3拦截器)

拦截http请求打印入参出参(Okhttp3拦截器)

前言

我们应用中经常出现请求其他三方接口,这也是经常会出错,找当时请求参数,返回结果比对的情况。如果自己加打印,很多时候会忘记。这里通过对Okhttp工具添加拦截器方式,将需要入参出参进行打印。

实践

一、引入maven 依赖

 <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.10.0</version>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

二、创建日志拦截器

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import okhttp3.*;
import okio.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author Administrator
 */
public class LoggingInterceptor implements Interceptor {

    private Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class);



    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        logForRequest(request);
        TimeInterval timer = DateUtil.timer();
        Response response =  chain.proceed(request);
        return logForResponse(response, timer);
    }

    private Response logForResponse(Response response, TimeInterval timer) {
        try {
            Response.Builder builder = response.newBuilder();
            Response clone = builder.build();
            logger.info("=========repose==log==start======");
            logger.info(String.format("repose url:%s,code:%s,time is:%s,headers:%s", clone.request().url(), clone.code(), timer.intervalMs() + "ms", clone.protocol()));

            ResponseBody body = clone.body();
            if (body != null) {
                MediaType mediaType = body.contentType();
                if (mediaType != null && isText(mediaType)) {
                    String content = body.string();
                    logger.info(String.format("message:%s,contentType:%s,content is:%s,", clone.message(), mediaType.toString(),content ));
                    body = ResponseBody.create(mediaType, content);
                    return response.newBuilder().body(body).build();
                }
            }
        } catch (Exception e) {
            logger.warn("print reponse error", e);
        }finally {
            logger.info("=========repose==log==end======");

        }
        return response;


    }

    private void logForRequest(Request request) {
        String url = request.url().toString();
        String method = request.method();
        Headers headers = request.headers();
        String headerStr = headers != null && headers.size() > 0 ? headers.toString() : "";
        logger.info("=========request==log==start======");
        logger.info(String.format("request url:%s,method:%s,headers:%s", url, method, headerStr));
        RequestBody requestBody = request.body();
        if (requestBody != null) {
            MediaType mediaType = requestBody.contentType();
            if (mediaType != null && isText(mediaType)) {
                logger.info("requestBody mediaType:%s,bodyToString:%s", mediaType.toString(), bodyToString(request));
            }
        }
        logger.info("=========request==log==end======");
    }

    private String bodyToString(final Request request) {
        final Request copy = request.newBuilder().build();
        final Buffer buffer=new Buffer();
        try {
            copy.body().writeTo(buffer);
        } catch (IOException e) {
            return "something error,when show requestBody";
        }
        return buffer.readUtf8();
    }


    private boolean isText(MediaType mediaType) {
        if (mediaType.type() != null && mediaType.type().equals("text")) {
            return true;
        }
        if (mediaType.subtype() != null) {
            if (mediaType.subtype().equals("json") ||
                    mediaType.subtype().equals("xml") ||
                    mediaType.subtype().equals("html") ||
                    mediaType.subtype().equals("webviewhtml")) {
                return true;
            }
        }
        return false;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100

三、使用Okhttp 工具类添加拦截器

package com.yin.common.util;

import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

public class OkHttpClientUtil {

    private static Logger logger = LoggerFactory.getLogger(OkHttpClientUtil.class);

    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static OkHttpClient client;
    static {
        client = new OkHttpClient.Builder()
                .readTimeout(20000, TimeUnit.MILLISECONDS)
                .writeTimeout(20000, TimeUnit.MILLISECONDS)
                .connectTimeout(20000, TimeUnit.MILLISECONDS)
                .addInterceptor(new LoggingInterceptor())
                .build();
    }



    public static final String doUpload(Map<String, String> params, Map<String, String> headerParam,
                                        final Map<String, File> fileMap, String mediaTypeStr, String url) {
        Response response = null;
        try {
            if (StringUtils.isEmpty(url)) {
                return null;
            }

            if (StringUtils.isEmpty(mediaTypeStr)) {
                mediaTypeStr = "application/octet-stream";
            }
            MediaType mediaType = MediaType.parse(mediaTypeStr);
            MultipartBody.Builder multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM);


            for (Map.Entry<String, File> fileEntry : fileMap.entrySet()) {
                File file = fileEntry.getValue();
                RequestBody fileBody = MultipartBody.create(mediaType, file);
                multipartBody.addFormDataPart(fileEntry.getKey(), file.getName(), fileBody);
            }
            if (!Objects.isNull(params) && params.size() > 0) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    multipartBody.addFormDataPart(entry.getKey(), entry.getValue());
                }
            }
            MultipartBody requestBody = multipartBody.build();
            Request.Builder builder = new Request.Builder();
            if (!Objects.isNull(headerParam) && headerParam.size() > 0) {
                for (Map.Entry<String, String> entry : headerParam.entrySet()) {
                    builder.addHeader(entry.getKey(), entry.getValue());
                }
            }
            Request request = builder.post(requestBody).url(url).build();
            response= client.newCall(request).execute();
            if (response.isSuccessful()) {
                return new String(response.body().bytes());
            }else {
                logger.error("[{}] having a error,param is:{}",url,String.valueOf(params));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }finally {
            if (!Objects.isNull(response)) {
                response.close();
            }
        }
        return "";
    }






    /**
     * get 请求
     * @param url       请求url地址
     * @return string
     * */
    public static String doGet(String url) {
        return doGet(url, null, null);
    }


    /**
     * get 请求
     * @param url       请求url地址
     * @param params    请求参数 map
     * @return string
     * */
    public String doGet(String url, Map<String, String> params) {
        return doGet(url, params, null);
    }




    /**
     * get 请求
     *
     * @param url     请求url地址
     * @param params  请求参数 map
     * @param headerMap 请求头字段
     * @return string
     */
    public static String doGet(String url, Map<String, String> params, Map<String, String> headerMap) {

        StringBuilder sb = new StringBuilder(url);
        if (params != null && params.keySet().size() > 0) {
            boolean firstFlag = true;
            for (String key : params.keySet()) {
                if (firstFlag) {
                    sb.append("?").append(key).append("=").append(params.get(key));
                    firstFlag = false;
                } else {
                    sb.append("&").append(key).append("=").append(params.get(key));
                }
            }
        }

        Request.Builder builder = new Request.Builder();
        if (headerMap != null && headerMap.size() > 0) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                builder.addHeader(entry.getKey(), entry.getValue());
            }
        }

        Request request = builder.url(sb.toString()).build();
        return execute(request);
    }

    /**
     * post 请求
     *
     * @param url    请求url地址
     * @param params 请求参数 map
     * @return string
     */
    public static String doPost(String url, Map<String, String> params, Map<String, String> headerParam) {

        FormBody formBody =addParamToBuilder(params);

        Request.Builder request = buildHeader(headerParam);

        Request buildRequest = request.post(formBody).url(url).build();

        return execute(buildRequest);
    }

    public static String doPut(String url, Map<String, String> params, Map<String, String> headerParam) {

        FormBody formBody =addParamToBuilder(params);

        Request.Builder request = buildHeader(headerParam);

        Request buildRequest = request.put(formBody).url(url).build();
        return execute(buildRequest);
    }

    public static String doDelete(String url, Map<String, String> params, Map<String, String> headerParam) {

        FormBody formBody =addParamToBuilder(params);

        Request.Builder request = buildHeader(headerParam);

        Request buildRequest = request.delete(formBody).url(url).build();
        logger.info("do delete request and url[{}]", url);
        return execute(buildRequest);
    }


    private static FormBody addParamToBuilder(Map<String, String> params){
        FormBody.Builder builder = new FormBody.Builder();

        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }

        return builder.build();
    }

    private static  Request.Builder buildHeader(Map<String, String> headerParam){
        Request.Builder request = new Request.Builder();
        if (!Objects.isNull(headerParam) && headerParam.size() > 0) {
            for (Map.Entry<String, String> entry : headerParam.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }
        return request;
    }
    /**
     * post 请求, 请求数据为 json 的字符串
     * @param url       请求url地址
     * @param json      请求数据, json 字符串
     * @return string
     */
    public static String doPostJson(String url,Map<String,String> headermap, String json) {
        return exectePost(url, json,headermap, JSON);
    }

    public static String doPutJson(String url, Map<String,String> headermap, String json) {
        return exectePut(url, json,headermap, JSON);
    }

    public static String doDeleteJson(String url, Map<String,String> headermap, String json) {
        return execteDelete(url, json,headermap, JSON);
    }



    private static String exectePost(String url, String data,Map<String,String> headerMap, MediaType contentType) {
        RequestBody requestBody = RequestBody.create(contentType, data);
        Request.Builder builder = buildHeader(headerMap);
        Request request = builder.post(requestBody).url(url).build();
        return execute(request);
    }

    private static String exectePut(String url, String data,Map<String,String> headerMap, MediaType contentType) {
        RequestBody requestBody = RequestBody.create(contentType, data);
        Request.Builder builder = buildHeader(headerMap);
        Request request = builder.put(requestBody).url(url).build();
        return execute(request);
    }

    private static String execteDelete(String url, String data, Map<String,String> headerMap,MediaType contentType) {
        RequestBody requestBody = RequestBody.create(contentType, data);
        Request.Builder builder = buildHeader(headerMap);
        Request request = builder.delete(requestBody).url(url).build();
        return execute(request);
    }




    private static String execute(Request request) {
        Response response = null;
        try {
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return new String(response.body().bytes());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return "";
    }

    public static void main(String[] args) {
        Map<String, String> param = new HashMap<>();
        Map<String, String> header = new HashMap<>();
        param.put("testParam","23");
        header.put("testHeader", "34");
        String s = OkHttpClientUtil.doGet("http://localhost:8028/mybatis", param, header);
        System.out.println("-----------"+s);
    }

}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/210776?site
推荐阅读
相关标签
  

闽ICP备14008679号