Hutool Http请求工具依据参数记录响应版

2024-01-11 09:21:47 浏览数 (1)

代码语言:javascript复制
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import static java.net.HttpURLConnection.HTTP_OK;

/**
 * 本工具是用于内网请求数据调试使用,会将请求响应的内容写入本地文件,下次请求时会先检查本地文件是否存在,如果存在则直接读取本地文件,不再发送请求。
 * 这样可以将本地文件拿出来,放到外网环境下,直接读取本地文件,就可以模拟内网环境下的请求。后续类似需求,可以修改本工具,实现更多功能。
 * <p>
 * 当前需求将cookie忽略掉!jadp每次加密的密码不一样,导致请求参数每次都不一样,就认为是新请求,就不再走缓存,导致报错。
 */
@Slf4j
public class HttpUtilsDebug {

    public static void main(String[] args) {
        String s = sendGet("https://www.zanglikun.com", "2");
    }

    // 将缓存文件夹设置为与项目代码同级的目录
    private static final String CACHE_FOLDER = System.getProperty("user.dir")   File.separator   "httpUtilDebug"   File.separator   "cache";

    // 确保缓存文件夹存在
    static {
        File cacheDir = new File(CACHE_FOLDER);
        if (!cacheDir.exists()) {
            cacheDir.mkdirs(); // 如果缓存文件夹不存在,则创建它
        }
    }

    // 发送 GET 请求
    public static String sendGet(String url, String cookie) {
        log.info("发送 GET 请求,URL: {}", url);
        String cacheKey = generateCacheKey(url, null, cookie);
        String cachedResponse = checkCache(cacheKey);
        if (cachedResponse != null) {
            return cachedResponse;
        }
        HttpResponse response = HttpRequest.get(url).cookie(cookie).execute();
        cacheResponse(url, null, cookie, response);
        return handleResponse(response);
    }

    // 发送 POST 请求
    public static String sendPost(String url, Map<String, Object> paramMap, String cookie) {
        log.info("发送 POST 请求,URL: {}, 参数: {}", url, paramMap);
        String cacheKey = generateCacheKey(url, paramMap, cookie);
        String cachedResponse = checkCache(cacheKey);
        if (cachedResponse != null) {
            return cachedResponse;
        }
        HttpResponse response = HttpRequest.post(url).cookie(cookie).form(paramMap).execute();
        cacheResponse(url, paramMap, cookie, response);
        return handleResponse(response);
    }

    // 发送 JSON 数据的 POST 请求
    public static String sendJsonPost(String url, Object jsonData) {
        String jsonString = JSONUtil.toJsonStr(jsonData);
        log.info("发送 JSON POST 请求,URL: {}, JSON 数据: {}", url, jsonString);
        String cacheKey = generateCacheKey(url, jsonString, null);
        String cachedResponse = checkCache(cacheKey);
        if (cachedResponse != null) {
            return cachedResponse;
        }
        HttpResponse response = HttpRequest.post(url).body(jsonString).execute();
        cacheResponse(url, jsonString, null, response);
        return handleResponse(response);
    }

    // 发送 JSON 数据的 POST 请求
    public static String sendJsonPostWithHeader(String url, Object jsonData, Map<String, String> headers) {
        String jsonString = JSONUtil.toJsonStr(jsonData);
        log.info("发送 JSON POST 请求,URL: {}, JSON 数据: {}", url, jsonString);
        String cacheKey = generateCacheKey(url, jsonString, null);
        String cachedResponse = checkCache(cacheKey);
        if (cachedResponse != null) {
            return cachedResponse;
        }
        HttpResponse response = HttpRequest.post(url).headerMap(headers, true).body(jsonString).execute();
        cacheResponse(url, jsonString, null, response);
        return handleResponse(response);
    }

    // 发送 JSON 数据的 POST 请求
    public static String sendJsonPost(String url, Object jsonData, String cookie) {
        String jsonString = JSONUtil.toJsonStr(jsonData);
        log.info("发送 JSON POST 请求,URL: {}, JSON 数据: {}", url, jsonString);
        String cacheKey = generateCacheKey(url, jsonString, cookie);
        String cachedResponse = checkCache(cacheKey);
        if (cachedResponse != null) {
            return cachedResponse;
        }
        HttpResponse response = HttpRequest.post(url).cookie(cookie).body(jsonString).execute();
        cacheResponse(url, jsonString, cookie, response);
        return handleResponse(response);
    }

    // 发送带请求头的 GET 请求
    public static String sendGetWithHeaders(String url, Map<String, String> headers) {
        log.info("发送带请求头的 GET 请求,URL: {}, 请求头: {}", url, headers);
        String cacheKey = generateCacheKey(url, null, headers);
        String cachedResponse = checkCache(cacheKey);
        if (cachedResponse != null) {
            return cachedResponse;
        }
        HttpResponse response = HttpRequest.get(url).headerMap(headers, true).execute();
        cacheResponse(url, null, headers, response);
        return handleResponse(response);
    }

    // 发送带请求头的 POST 请求
    public static String sendPostWithHeaders(String url, Map<String, Object> paramMap, Map<String, String> headers) {
        log.info("发送带请求头的 POST 请求,URL: {}, 参数: {}, 请求头: {}", url, paramMap, headers);
        String cacheKey = generateCacheKey(url, paramMap, headers);
        String cachedResponse = checkCache(cacheKey);
        if (cachedResponse != null) {
            return cachedResponse;
        }
        HttpResponse response = HttpRequest.post(url).form(paramMap).headerMap(headers, true).execute();
        cacheResponse(url, paramMap, headers, response);
        return handleResponse(response);
    }

    // 发送带请求头的 POST 请求
    public static String sendDeleteWithHeaders(String url, String cookie) {
        log.info("发送带请求头的 Delete 请求,URL: {}", url);
        HttpResponse response = HttpRequest.delete(url).contentType("application/json").cookie(cookie).execute();
        return handleResponse(response);
    }

    // 处理响应
    public static String handleResponse(HttpResponse response) {
        int status = response.getStatus();
        if (status == HTTP_OK) {
            String responseBody = response.body();
            log.info("请求成功,状态码:{}, 响应内容:{}", status, responseBody);
            return responseBody;
        } else {
            // 可根据实际需求处理其他状态码
            throw new RuntimeException("请求失败,状态码:"   status);
        }
    }

    // 缓存响应
    private static void cacheResponse(String url, Object params, Object headersOrCookie, HttpResponse response) {
        String cacheKey = generateCacheKey(url, params, headersOrCookie);
        String cacheFilePath = CACHE_FOLDER   File.separator   cacheKey   ".txt";
        try {
            FileUtil.writeString(response.body(), cacheFilePath, "UTF-8");
        } catch (Exception e) {
            log.error("缓存响应时出错:", e);
        }
    }

    // 生成缓存文件的键
    private static String generateCacheKey(String url, Object params, Object headersOrCookie) {
        String paramsString = params != null ? params.toString() : "";
        String headersOrCookieString = headersOrCookie != null ? headersOrCookie.toString() : "";
        // 使用 URL、参数和 cookie/header 生成一个唯一的缓存键
        String rawCacheKey = url   paramsString; // 忽略掉cookie   headersOrCookieString;
        // 使用 MD5 生成一个较短的键名
        return DigestUtil.md5Hex(rawCacheKey);
    }

    // 检查缓存
    private static String checkCache(String cacheKey) {
        String cacheFilePath = CACHE_FOLDER   File.separator   cacheKey   ".txt";
        if (FileUtil.exist(cacheFilePath)) {
            log.info("缓存命中,读取缓存内容:{}", cacheFilePath);
            return FileUtil.readString(cacheFilePath, "UTF-8");
        } else {
            // 缓存未命中,尝试从resources目录读取
            String resourcePath = "/httpUtilDebug/cache/"   cacheKey   ".txt";
            InputStream inputStream = HttpUtil.class.getResourceAsStream(resourcePath);
            if (inputStream != null) {
                try {
                    log.info("从resources目录读取缓存内容:{}", resourcePath);
                    return IoUtil.read(inputStream, StandardCharsets.UTF_8);
                } catch (Exception e) {
                    log.error("从resources目录读取文件时出错:", e);
                } finally {
                    IoUtil.close(inputStream);
                }
            }
        }
        return null;
    }


}

特殊说明: 上述文章均是作者实际操作后产出。烦请各位,请勿直接盗用!转载记得标注原文链接:www.zanglikun.com 第三方平台不会及时更新本文最新内容。如果发现本文资料不全,可访问本人的Java博客搜索:标题关键字。

0 人点赞