Skip to content

Instantly share code, notes, and snippets.

@OleksandrKucherenko
Created May 26, 2017 15:27
Show Gist options
  • Save OleksandrKucherenko/b626877f56ec0dd39f3c7ee536940453 to your computer and use it in GitHub Desktop.
Save OleksandrKucherenko/b626877f56ec0dd39f3c7ee536940453 to your computer and use it in GitHub Desktop.
package /* YOUR PROJECT PACKAGE */.utils;
import android.support.annotation.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import okhttp3.Dns;
import rx.Observable;
import rx.schedulers.Schedulers;
/** implements DNS lookup/resolve client with timeout feature. */
public class DnsEx implements Dns {
/** Empty instance used as indicator of TIMEOUT exception. */
private static final List<InetAddress> TIMEOUT = Collections.emptyList();
/** timeout in millis. */
private final long mTimeoutDns;
/** Hidden constructor. */
private DnsEx(final long dnsTimeoutMillis) {
mTimeoutDns = dnsTimeoutMillis;
}
/** Create a new instance with specific timeout. */
@NonNull
public static DnsEx timeout(final int time, @NonNull final TimeUnit units) {
final long millis = units.toMillis(time);
return new DnsEx(millis);
}
/** {@inheritDoc} */
@Override
public List<InetAddress> lookup(@NonNull final String address) throws UnknownHostException {
final List<InetAddress> results = Observable.fromCallable(
new Callable<List<InetAddress>>() {
@Override
public List<InetAddress> call() throws Exception {
return Dns.SYSTEM.lookup(address);
}
})
.subscribeOn(Schedulers.computation())
.timeout(mTimeoutDns, TimeUnit.MILLISECONDS, Observable.just(TIMEOUT))
.toBlocking()
.firstOrDefault(TIMEOUT);
if (TIMEOUT == results) {
final String message = "Cannot resolve '" + address + "' in " + mTimeoutDns + " ms.";
// wrap Timeout exception into UnknownHostException
final UnknownHostException unknown = new UnknownHostException(address);
unknown.initCause(new TimeoutException(message));
throw unknown;
}
return results;
}
}
@OleksandrKucherenko
Copy link
Author

usage:

        return new OkHttpClient.Builder()
                .connectTimeout(TIMEOUT_CONNECT, TimeUnit.SECONDS)
                .readTimeout(TIMEOUT_READ, TimeUnit.SECONDS)
                .writeTimeout(TIMEOUT_WRITE, TimeUnit.SECONDS)
                .dns(DnsEx.timeout(TIMEOUT_DNS, TimeUnit.SECONDS))
                .addInterceptor(logging)
                .build();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment