将RequestBody以json格式保存到本地TXT文件中

本文介绍了一种在接口报错时,将请求参数以JSON格式保存至本地的方法,便于使用Postman进行调试。通过自定义工具类,实现了RequestBody的解析与文本文件的写入,有效提升了接口调试效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:接口报错时,将接口请求参数(RequestBody)以json格式保存到本地 txt文件中,方便postman调试。

方法:

public class FileUtils {

    /**
     * 将RequestBody转换成json字符串
     *
     * @param body
     * @return
     */
	public static String parseParams(RequestBody body) {
        try {

            if (body == null) return "";
            Buffer requestBuffer = new Buffer();
            body.writeTo(requestBuffer);
            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = body.contentType();

            if (contentType != null) {
                charset = contentType.charset(charset);
            }
            String text = requestBuffer.readString(charset);

            if (contentType != null && !"json".equals(contentType.subtype())) {
                text = URLDecoder.decode(text, convertCharset(charset));
            }

            return TextUtil.jsonFormat(text);
        } catch (IOException e) {
            return "{\"error\": \"" + e.getMessage() + "\"}";
        }
    }

    private static String convertCharset(Charset charset) {
        String s = charset.toString();
        int i = s.indexOf("[");
        if (i == -1)
            return s;
        return s.substring(i + 1, s.length() - 1);
    }
    
 	/**
     * 将字符串写入到文本文件中
     * https://blog.youkuaiyun.com/u012246458/article/details/83063112
     *
     * @param content
     */
    public static void writeTxtToFile(String content) {
        String filePath = MyConstants.REQUEST_LOG_DIR;
        // 每次写入时,都换行写
        String strContent = "请求日期:" + DatetimeUtil.getCurrent() + "\r\n" + content + "\r\n\r\n";
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            LegoLog.w(e.getMessage());
        }
    }
}

调用:

@Override
public final void onResponse(Call<HttpBaseResult<T>> call, Response<HttpBaseResult<T>> response) {
    onComplete();
    // 接口异常,保存接口请求参数,便于调试
   saveErrorRequest(call, baseBean.getStatus() + ",," + baseBean.getMessage());
}


    /**
     * 接口异常时,保存接口请求参数,便于调试。
     *
     * @param call 请求参数
     * @param <T>  类型
     */
    private <T> void saveErrorRequest(Call<HttpBaseResult<T>> call, String message) {
        if (call != null && call.request() != null) {
            Request request = call.request();
            RequestBody body = request.body();

            String logBuffer = "URL:" + request.url().toString() + "\r\n" +
                    "Method:" + request.method() + "\r\n" +
                    "Body:" + FileUtils.parseParams(body) + "\r\n" +
                    "Message:" + message;
            FileUtils.writeTxtToFile(logBuffer);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值