ProtoUtil.java
2.7 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package cn.living.sharecenter.utils;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ProtoUtil {
public static RequestProto getRequestProto(HttpRequest httpRequest) {
RequestProto requestProto = new RequestProto();
int port = -1;
String hostStr = httpRequest.headers().get(HttpHeaderNames.HOST);
if (hostStr == null) {
Pattern pattern = Pattern.compile("^(?:https?://)?(?<host>[^/]*)/?.*$");
Matcher matcher = pattern.matcher(httpRequest.uri());
if (matcher.find()) {
hostStr = matcher.group("host");
} else {
return null;
}
}
String uriStr = httpRequest.uri();
Pattern pattern = Pattern.compile("^(?:https?://)?(?<host>[^:]*)(?::(?<port>\\d+))?(/.*)?$");
Matcher matcher = pattern.matcher(hostStr);
//先从host上取端口号没取到再从uri上取端口号 issues#4
String portTemp = null;
if (matcher.find()) {
requestProto.setHost(matcher.group("host"));
portTemp = matcher.group("port");
if (portTemp == null) {
matcher = pattern.matcher(uriStr);
if (matcher.find()) {
portTemp = matcher.group("port");
}
}
}
if (portTemp != null) {
port = Integer.parseInt(portTemp);
}
boolean isSsl = uriStr.indexOf("https") == 0 || hostStr.indexOf("https") == 0;
if (port == -1) {
if (isSsl) {
port = 443;
} else {
port = 80;
}
}
requestProto.setPort(port);
requestProto.setSsl(isSsl);
return requestProto;
}
public static class RequestProto implements Serializable {
private static final long serialVersionUID = -6471051659605127698L;
private String host;
private int port;
private boolean ssl;
public RequestProto() {
}
public RequestProto(String host, int port, boolean ssl) {
this.host = host;
this.port = port;
this.ssl = ssl;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public boolean getSsl() {
return ssl;
}
public void setSsl(boolean ssl) {
this.ssl = ssl;
}
}
}