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 命令