Skip to content

Commit

Permalink
fix: handle case where URI.getHost() returns null (#484)
Browse files Browse the repository at this point in the history
It seems that URI.getHost() might return null on some Samsung devices.

Related: https://stackoverflow.com/questions/39645789/android-websocket-connection-failed-galaxy-s4
  • Loading branch information
arghaffari authored and darrachequesne committed Dec 10, 2020
1 parent 858907f commit 567372e
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/main/java/io/socket/client/Url.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,16 @@
import java.net.URISyntaxException;
import java.net.URL;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Url {

private static Pattern PATTERN_HTTP = Pattern.compile("^http|ws$");
private static Pattern PATTERN_HTTPS = Pattern.compile("^(http|ws)s$");
/**
* Expected format: "[id:password@]host[:port]"
*/
private static Pattern PATTERN_AUTHORITY = Pattern.compile("^(.*@)?([^:]+)(:\\d+)?$");

private Url() {}

Expand Down Expand Up @@ -40,10 +45,15 @@ public static URL parse(URI uri) {
String userInfo = uri.getRawUserInfo();
String query = uri.getRawQuery();
String fragment = uri.getRawFragment();
String _host = uri.getHost();
if (_host == null) {
// might happen on some of Samsung Devices such as S4.
_host = extractHostFromAuthorityPart(uri.getRawAuthority());
}
try {
return new URL(protocol + "://"
+ (userInfo != null ? userInfo + "@" : "")
+ uri.getHost()
+ _host
+ (port != -1 ? ":" + port : "")
+ path
+ (query != null ? "?" + query : "")
Expand All @@ -70,4 +80,21 @@ public static String extractId(URL url) {
return protocol + "://" + url.getHost() + ":" + port;
}

private static String extractHostFromAuthorityPart(String authority)
{
if (authority == null) {
throw new RuntimeException("unable to parse the host from the authority");
}

Matcher matcher = PATTERN_AUTHORITY.matcher(authority);

// If the authority part does not match the expected format.
if (!matcher.matches()) {
throw new RuntimeException("unable to parse the host from the authority");
}

// Return the host part.
return matcher.group(2);
}

}

0 comments on commit 567372e

Please sign in to comment.