How to set HttpResponse timeout for Android in Java

后端 未结 10 2199
刺人心
刺人心 2020-11-22 08:02

I have created the following function for checking the connection status:

private void checkConnectionStatus() {
    HttpClient httpClient = new DefaultHttpC         


        
10条回答
  •  无人共我
    2020-11-22 08:37

    For those saying that the answer of @kuester2000 does not work, please be aware that HTTP requests, first try to find the host IP with a DNS request and then makes the actual HTTP request to the server, so you may also need to set a timeout for the DNS request.

    If your code worked without the timeout for the DNS request it's because you are able to reach a DNS server or you are hitting the Android DNS cache. By the way you can clear this cache by restarting the device.

    This code extends the original answer to include a manual DNS lookup with a custom timeout:

    //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
    

    Used method:

    //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());
    }   
    

    This class is from this blog post. Go and check the remarks if you will use it.

    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;
        }
    }
    

提交回复
热议问题