Java 开发常用代码块之一

HTTP 请求

正则表达式解析 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
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);
matcher.find();

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;
}

}