Java教程

Java HttpServletRequest 转 CURL 命令

本文主要是介绍Java HttpServletRequest 转 CURL 命令,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Java HttpServletRequest 转 CURL 命令

private static final String FORMAT_HEADER = "-H \"%1$s:%2$s\"";
private static final String FORMAT_METHOD = "-X %1$s";
private static final String FORMAT_BODY = "-d '%1$s'";
private static final String FORMAT_URL = "\"%1$s\"";
private static final String CONTENT_TYPE = "Content-Type";
    
public String getCurl(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        List<String> parts = new ArrayList<>();
        parts.add("curl");
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String contentType = request.getContentType();
        String queryString = request.getQueryString();
        parts.add(String.format(FORMAT_METHOD, method.toUpperCase()));

        Map<String, String> headers = new HashMap<>(16);
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            headers.put(key, request.getHeader(key));
        }
        headers.forEach((k, v) -> parts.add(String.format(FORMAT_HEADER, k, v)));
        if (StrUtil.isNotEmpty(contentType) && !headers.containsKey(CONTENT_TYPE)) {
            parts.add(String.format(FORMAT_HEADER, CONTENT_TYPE, contentType));
        }
        if (StrUtil.isNotEmpty(queryString)) {
            url = HttpUtil.urlWithForm(url, queryString, CharsetUtil.CHARSET_UTF_8, false);
        }
        String body = null;
        try {
            body = IoUtil.readUtf8(request.getInputStream());
        } catch (IOException ignore) {
        }
        if (StrUtil.isNotEmpty(body)) {
            parts.add(String.format(FORMAT_BODY, body));
        }
        parts.add(String.format(FORMAT_URL, url));
        return StrUtil.join(" ", parts);
    }
这篇关于Java HttpServletRequest 转 CURL 命令的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!