IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> 拦截http请求打印入参出参(Okhttp3拦截器) -> 正文阅读

[网络协议]拦截http请求打印入参出参(Okhttp3拦截器)

前言

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

实践

一、引入maven 依赖

 <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.10.0</version>
        </dependency>

二、创建日志拦截器

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;
    }
}

三、使用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);
    }

}


  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-11-28 11:37:38  更:2021-11-28 11:37:40 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/26 8:39:33-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码