55import java .net .URISyntaxException ;
66import java .net .URL ;
77import java .util .regex .Pattern ;
8+ import java .util .regex .Matcher ;
89
910public class Url {
1011
1112 private static Pattern PATTERN_HTTP = Pattern .compile ("^http|ws$" );
1213 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+)?$" );
1318
1419 private Url () {}
1520
@@ -40,10 +45,15 @@ public static URL parse(URI uri) {
4045 String userInfo = uri .getRawUserInfo ();
4146 String query = uri .getRawQuery ();
4247 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+ }
4353 try {
4454 return new URL (protocol + "://"
4555 + (userInfo != null ? userInfo + "@" : "" )
46- + uri . getHost ()
56+ + _host
4757 + (port != -1 ? ":" + port : "" )
4858 + path
4959 + (query != null ? "?" + query : "" )
@@ -70,4 +80,21 @@ public static String extractId(URL url) {
7080 return protocol + "://" + url .getHost () + ":" + port ;
7181 }
7282
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+
73100}
0 commit comments