Java 开发常用代码块之一

网络编程

获取 IP 地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import cn.hutool.core.util.StrUtil;
import javax.servlet.http.HttpServletRequest;

/**
* IP地址工具
*/
public class IPUtils {

/**
* 获取IP地址
* 如果使用Nginx等反向代理软件,不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = null;
try {
ip = request.getHeader("x-forwarded-for");
if (StrUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StrUtil.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StrUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StrUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StrUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
System.out.println("IPUtils ERROR " + e.getLocalizedMessage());
}
return ip;
}

}

正则表达式解析 URL

通过正则表达式,获取 URL 中的协议、域名、端口、URI。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import cn.hutool.core.util.StrUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HttpUtil {

public static final String HTTP_PROTOCOL = "http://";

public static final String HTTPS_PROTOCOL = "https://";

/**
* 解析URL(包括协议、域名、端口、URI)
*
* @param url
* @return
*/
public static Map<String, String> parseUrl(String url) {
Map<String, String> map = new HashMap(4);
try {
Pattern pattern = Pattern.compile("(https?://)([^:^/]*)(:\\d*)?(.*)?");
Matcher matcher = pattern.matcher(url);
boolean findResult = matcher.find();
if (!findResult) {
return map;
}

String protocol = matcher.group(1);
String domain = matcher.group(2);
String port = matcher.group(3);
String uri = matcher.group(4);

if (StrUtil.isBlank(port)) {
if (HTTP_PROTOCOL.equals(protocol)) {
port = "80";
} else if (HTTPS_PROTOCOL.equals(protocol)) {
port = "443";
} else {
port = "unknown";
}
} else {
port = port.replace(":", "");
}

map.put("protocol", protocol);
map.put("domain", domain);
map.put("port", port);
map.put("uri", uri);
} catch (Exception e) {
e.printStackTrace();
}
return map;
}

}