Bagi mereka yang mengatakan bahwa jawaban @ kuester2000 tidak berfungsi, harap perhatikan bahwa permintaan HTTP, pertama-tama coba temukan IP host dengan permintaan DNS dan kemudian buat permintaan HTTP aktual ke server, jadi Anda mungkin juga perlu mengatur batas waktu untuk permintaan DNS.
Jika kode Anda berfungsi tanpa batas waktu untuk permintaan DNS, itu karena Anda dapat mencapai server DNS atau Anda menekan cache Android DNS. Omong-omong, Anda dapat menghapus cache ini dengan memulai ulang perangkat.
Kode ini memperluas jawaban asli untuk menyertakan pencarian DNS manual dengan batas waktu khusus:
//Our objective
String sURL = "http://www.google.com/";
int DNSTimeout = 1000;
int HTTPTimeout = 2000;
//Get the IP of the Host
URL url= null;
try {
url = ResolveHostIP(sURL,DNSTimeout);
} catch (MalformedURLException e) {
Log.d("INFO",e.getMessage());
}
if(url==null){
//the DNS lookup timed out or failed.
}
//Build the request parameters
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, HTTPTimeout);
HttpConnectionParams.setSoTimeout(params, HTTPTimeout);
DefaultHttpClient client = new DefaultHttpClient(params);
HttpResponse httpResponse;
String text;
try {
//Execute the request (here it blocks the execution until finished or a timeout)
httpResponse = client.execute(new HttpGet(url.toString()));
} catch (IOException e) {
//If you hit this probably the connection timed out
Log.d("INFO",e.getMessage());
}
//If you get here everything went OK so check response code, body or whatever
Metode yang digunakan:
//Run the DNS lookup manually to be able to time it out.
public static URL ResolveHostIP (String sURL, int timeout) throws MalformedURLException {
URL url= new URL(sURL);
//Resolve the host IP on a new thread
DNSResolver dnsRes = new DNSResolver(url.getHost());
Thread t = new Thread(dnsRes);
t.start();
//Join the thread for some time
try {
t.join(timeout);
} catch (InterruptedException e) {
Log.d("DEBUG", "DNS lookup interrupted");
return null;
}
//get the IP of the host
InetAddress inetAddr = dnsRes.get();
if(inetAddr==null) {
Log.d("DEBUG", "DNS timed out.");
return null;
}
//rebuild the URL with the IP and return it
Log.d("DEBUG", "DNS solved.");
return new URL(url.getProtocol(),inetAddr.getHostAddress(),url.getPort(),url.getFile());
}
Kelas ini dari posting blog ini . Pergi dan periksa pernyataan apakah Anda akan menggunakannya.
public static class DNSResolver implements Runnable {
private String domain;
private InetAddress inetAddr;
public DNSResolver(String domain) {
this.domain = domain;
}
public void run() {
try {
InetAddress addr = InetAddress.getByName(domain);
set(addr);
} catch (UnknownHostException e) {
}
}
public synchronized void set(InetAddress inetAddr) {
this.inetAddr = inetAddr;
}
public synchronized InetAddress get() {
return inetAddr;
}
}