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";
/**
* <p>
* HttpServletRequest 转化为 CURL 命令
* </p>
*
* @param request request
* @return String
* @author Tophua
* @since 2021/8/19
*/
public String getCurl(HttpServletRequest request) {
String curl;
try {
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);
}
if (ContentType.isFormUrlEncode(contentType) && CollUtil.isNotEmpty(request.getParameterMap())) {
request.getParameterMap().forEach((k, v) ->
parts.add(StrUtil.format("--data-urlencode '{}={}'", k, ArrayUtil.get(v, 0))));
}
if (StrUtil.startWithIgnoreCase(contentType, ContentType.JSON.toString())) {
BodyReaderHttpServletRequestWrapper wrapper = (BodyReaderHttpServletRequestWrapper) request;
String body = StrUtil.utf8Str(wrapper.getCachedBody());
if (StrUtil.isNotEmpty(body)) {
parts.add(String.format(FORMAT_BODY, body));
}
}
parts.add(String.format(FORMAT_URL, url));
curl = StrUtil.join(" ", parts);
} catch (Exception e) {
e.printStackTrace();
curl = null;
}
return curl;
}
热爱生活,热爱代码!
做一个有思想、有灵魂的程序员!