com.feingto.cloud.kit.HttpKit Maven / Gradle / Ivy
package com.feingto.cloud.kit;
import com.feingto.cloud.dto.KeyValue;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.util.DigestUtils;
import org.springframework.util.StreamUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* Http 工具类
*
* @author longfei
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class HttpKit {
private static Logger logger = LoggerFactory.getLogger(HttpKit.class);
/**
* 生成唯一Key
*/
public static String generateKey(String uri, Map queryParams) {
StringBuilder sb = new StringBuilder();
queryParams.keySet().forEach(k -> sb.append(":").append(queryParams.get(k)));
return uri + ":" + DigestUtils.md5DigestAsHex(sb.toString().getBytes());
}
/**
* 生成唯一Key
*/
public static String generateKey(String uri, byte[] bytes) {
return uri + ":" + DigestUtils.md5DigestAsHex(bytes);
}
/**
* 获取Json提交的数据
*/
public static byte[] getRequestJson(HttpServletRequest request) throws IOException {
Charset charset = Optional.of(Charset.forName(request.getCharacterEncoding())).orElse(StandardCharsets.UTF_8);
if (HttpMethod.GET.name().equals(request.getMethod())) {
return StringUtils.isNoneBlank(request.getQueryString()) ? request.getQueryString().getBytes(charset) : new byte[0];
} else {
return StreamUtils.copyToByteArray(request.getInputStream());
}
}
/**
* 是否Path表达式"##"的路径: /#path#/user
*/
public static boolean isEnvVariable(String path) {
return path.contains("#");
}
/**
* 是否Path表达式"{}"的路径: /order/{id}
*/
public static boolean isPathVariable(String path) {
return path.contains("{") && path.contains("}");
}
/**
* 转换Path表达式"##"
* 以url里面"#"对里的字符串作为key查找map对应的值,以此值替换url里面"#"对里的字符串
* 例如: /#path#/id-> /test/id
*/
public static String parshPathEnv(String path, List params) {
Map paramsMap = Maps.newLinkedHashMap();
params.forEach(keyValue -> paramsMap.put(keyValue.getKey(), (String) keyValue.getValue()));
String regex = "\\#(" + StringUtils.join(paramsMap.keySet(), "|") + ")\\#";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(path);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, paramsMap.get(matcher.group(1)));
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* 转换Path表达式"{}"
* 以url里面"{}"对里的字符串作为key查找map对应的值,以此值替换url里面"{}"对里的字符串
* 例如: /test/{id}-> /test/1
*/
public static String parsePath(String path, Map pathParams) {
String prefix = StringUtils.substringBefore(path, "{");
String last = StringUtils.substringAfterLast(path, "}");
return prefix + Stream.of(path)
.map(p -> StringUtils.substringsBetween(p, "{", "}"))
.flatMap(Arrays::stream)
.map(pathParams::get)
.collect(Collectors.joining("/")) + last;
}
/**
* 转换Path表达式的url参数Map
*/
public static Map stringToPathParamsMap(String path, String uri) {
uri = EncodeKit.urlDecode(uri);// UTF8(URL)解码
Map pathParams = Maps.newLinkedHashMap();
String[] paramNames = StringUtils.substringsBetween(path, "{", "}");
// 获取Path参数值
String[] paramValues = StringUtils.substringBefore(StringUtils.substringAfter(uri, StringUtils.substringBefore(path, "{")), "?").split("/");
if (paramNames != null) {
IntStream.range(0, paramNames.length).forEach(i -> pathParams.put(paramNames[i], paramValues[i]));
}
return pathParams;
}
/**
* 参数拼接url参数字符串
*/
public static StringBuffer paramsMapToString(Map params) {
StringBuffer requestParams = new StringBuffer();
if (params != null) {
params.forEach((k, v) -> requestParams.append(k).append("=").append(v).append("&"));
}
return requestParams;
}
public static boolean isAjaxWithRequest(HttpServletRequest request) {
if (request != null) {
if (request.getHeader("x-requested-with") == null) {
return "*/*".equals(request.getHeader("accept"))
|| "true".equals(request.getParameter("_SYSTEM_REQUEST_FROM_000"));
}
return request.getHeader("x-requested-with").equals("XMLHttpRequest");
}
return false;
}
public static void setCookie(HttpServletResponse response, String name, String value) {
setCookie(response, name, value, 86400);
}
public static void setCookie(HttpServletResponse response, String name, String value, String path) {
setCookie(response, name, value, path, 86400);
}
public static void setCookie(HttpServletResponse response, String name, String value, int maxAge) {
setCookie(response, name, value, "/", maxAge);
}
public static void setCookie(HttpServletResponse response, String name, String value, String path, int maxAge) {
Cookie cookie = new Cookie(name, null);
cookie.setPath(path);
cookie.setMaxAge(maxAge);
try {
cookie.setValue(URLEncoder.encode(value, "utf-8"));
} catch (UnsupportedEncodingException ignored) {
}
response.addCookie(cookie);
}
public static String getCookie(HttpServletRequest request, String name) {
return getCookie(request, null, name, false);
}
public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name) {
return getCookie(request, response, name, true);
}
public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, boolean isRemove) {
String value = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
Cookie cookie;
for (Cookie cooky : cookies) {
cookie = cooky;
if (cookie.getName().equals(name)) {
try {
value = URLDecoder.decode(cookie.getValue(), "UTF-8");
} catch (UnsupportedEncodingException ignored) {
}
if (isRemove) {
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
}
}
return value;
}
public static String getRequestAddr(HttpServletRequest request) {
if (request == null) {
return "";
} else {
String ip = request.getRemoteAddr();
if ("0:0:0:0:0:0:0:1".equals(ip) || "127.0.0.1".equals(ip)) {
ip = "本地主机";
}
return ip;
}
}
/**
* 获取当前网络ip
*/
public static String getIpAddr(HttpServletRequest request) {
String ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
// 根据网卡取本机配置的IP
try {
ipAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException ignored) {
}
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ipAddress != null && ipAddress.contains(",")) {
ipAddress = ipAddress.split(",")[0];
}
return ipAddress;
}
public static String getBrowser(HttpServletRequest request) {
String browser = "未知";
if (request != null) {
try {
String ua = getUserAgent(request);
int idx;
if (ua.contains("MSIE")) {
idx = ua.indexOf("MSIE");
browser = ua.substring(idx, ua.indexOf(";", idx));
} else if (ua.contains("Edge/")) {
idx = ua.indexOf("Edge/");
browser = ua.substring(idx);
} else if (ua.contains("gecko") && ua.contains("rv:11.0")) {
browser = "MSIE 11.0";
} else if (ua.contains("OPR/")) {
idx = ua.indexOf("OPR/");
browser = ua.substring(idx);
browser = browser.replace("OPR", "Opera");
} else if (ua.contains("Chrome/")) {
idx = ua.indexOf("Chrome");
browser = ua.substring(idx, ua.indexOf(" ", idx));
} else if (ua.contains("Firefox/")) {
idx = ua.indexOf("Firefox/");
browser = ua.substring(idx);
} else if (ua.contains("Safari/")) {
idx = ua.indexOf("Safari/");
browser = ua.substring(idx);
}
} catch (Exception var4) {
browser = "未知";
}
}
return browser;
}
public static String getPlatform(HttpServletRequest request) {
String platform = "未知";
if (request != null) {
String ua = getUserAgent(request);
if (ua.contains("Windows Phone")) {
platform = "Windows Phone";
} else if (ua.contains("Windows")) {
platform = "Windows";
if (ua.contains("Windows NT 10.0")) {
platform = "Windows 10";
} else if (ua.contains("Windows NT 6.3")) {
platform = "Windows 8.1";
} else if (ua.contains("Windows NT 6.2")) {
platform = "Windows 8";
} else if (ua.contains("Windows NT 6.1")) {
platform = "Windows 7";
} else if (ua.contains("Windows NT 6.0")) {
platform = "Windows Vista";
} else if (ua.contains("Windows NT 5.1")) {
platform = "Windows XP";
}
} else if (ua.contains("iPad")) {
platform = "iPad";
} else if (ua.contains("iPhone")) {
platform = "iPhone";
} else if (ua.contains("Android")) {
platform = "Android";
} else if (ua.contains("Linux")) {
platform = "Linux";
}
}
return platform;
}
public static String getUserAgent(HttpServletRequest request) {
String userAgent = "";
if (request != null) {
userAgent = request.getHeader("user-agent");
}
return userAgent;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy