try to fix null proxySelector issue with okhttp

This commit is contained in:
Luck 2018-02-15 22:20:11 +00:00
parent a3730aceeb
commit b8c5c60ece
No known key found for this signature in database
GPG Key ID: EFA9B3EC5FD90F8B

View File

@ -32,6 +32,12 @@ import okhttp3.Response;
import okhttp3.ResponseBody;
import java.io.IOException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.util.Collections;
import java.util.List;
/**
* Utilities for the OkHttp client
@ -43,6 +49,7 @@ public class HttpClient {
private synchronized static OkHttpClient getClient() {
if (client == null) {
client = new OkHttpClient.Builder()
.proxySelector(new NullSafeProxySelector())
.addInterceptor(new LuckPermsUserAgentInterceptor())
.build();
}
@ -81,6 +88,28 @@ public class HttpClient {
}
}
// sometimes ProxySelector#getDefault returns null, and okhttp doesn't like that
private static final class NullSafeProxySelector extends ProxySelector {
private static final List<Proxy> DIRECT = Collections.singletonList(Proxy.NO_PROXY);
@Override
public List<Proxy> select(URI uri) {
ProxySelector def = ProxySelector.getDefault();
if (def == null) {
return DIRECT;
}
return def.select(uri);
}
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
ProxySelector def = ProxySelector.getDefault();
if (def != null) {
def.connectFailed(uri, sa, ioe);
}
}
}
private HttpClient() {}
}