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

需求:接口報錯時,將接口請求參數(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.csdn.net/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";
        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();
    // 接口異常,保存接口請求參數,便於調試
    if (call != null && call.request() != null) {
        RequestBody body = call.request().body();
        FileUtils.writeTxtToFile(FileUtils.parseParams(body));
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章