赞
踩
我们应用中经常出现请求其他三方接口,这也是经常会出错,找当时请求参数,返回结果比对的情况。如果自己加打印,很多时候会忘记。这里通过对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); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。