5
5
import java .net .URISyntaxException ;
6
6
import java .net .URL ;
7
7
import java .util .regex .Pattern ;
8
+ import java .util .regex .Matcher ;
8
9
9
10
public class Url {
10
11
11
12
private static Pattern PATTERN_HTTP = Pattern .compile ("^http|ws$" );
12
13
private static Pattern PATTERN_HTTPS = Pattern .compile ("^(http|ws)s$" );
14
+ /**
15
+ * Expected format: "[id:password@]host[:port]"
16
+ */
17
+ private static Pattern PATTERN_AUTHORITY = Pattern .compile ("^(.*@)?([^:]+)(:\\ d+)?$" );
13
18
14
19
private Url () {}
15
20
@@ -40,10 +45,15 @@ public static URL parse(URI uri) {
40
45
String userInfo = uri .getRawUserInfo ();
41
46
String query = uri .getRawQuery ();
42
47
String fragment = uri .getRawFragment ();
48
+ String _host = uri .getHost ();
49
+ if (_host == null ) {
50
+ // might happen on some of Samsung Devices such as S4.
51
+ _host = extractHostFromAuthorityPart (uri .getRawAuthority ());
52
+ }
43
53
try {
44
54
return new URL (protocol + "://"
45
55
+ (userInfo != null ? userInfo + "@" : "" )
46
- + uri . getHost ()
56
+ + _host
47
57
+ (port != -1 ? ":" + port : "" )
48
58
+ path
49
59
+ (query != null ? "?" + query : "" )
@@ -70,4 +80,21 @@ public static String extractId(URL url) {
70
80
return protocol + "://" + url .getHost () + ":" + port ;
71
81
}
72
82
83
+ private static String extractHostFromAuthorityPart (String authority )
84
+ {
85
+ if (authority == null ) {
86
+ throw new RuntimeException ("unable to parse the host from the authority" );
87
+ }
88
+
89
+ Matcher matcher = PATTERN_AUTHORITY .matcher (authority );
90
+
91
+ // If the authority part does not match the expected format.
92
+ if (!matcher .matches ()) {
93
+ throw new RuntimeException ("unable to parse the host from the authority" );
94
+ }
95
+
96
+ // Return the host part.
97
+ return matcher .group (2 );
98
+ }
99
+
73
100
}
0 commit comments