Android: How to set a HTTP connection timeout and react to it?

后端 未结 2 867
感情败类
感情败类 2020-12-21 12:51

I am working on an Android app that needs to read a line from a web page right when it starts. I am doing this with the following code:

try{
        URL url          


        
2条回答
  •  醉梦人生
    2020-12-21 13:30

    Probably better solution if you setConnectionTimeout to 5 sec, catch SocketTimeoutException and show Toast from there. When you set ConnectionTimeout to some value and connection didn't get response code will throw SocketTimeoutException. Here you can catch it and call handler to show a toast in UI. Finally will close the connection and release memory.

    class MyHttpClient extends DefaultHttpClient {
        @Override
        protected ClientConnectionManager createClientConnectionManager() {
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            registry.register(new Scheme("https", 
                mSSLSocketFactory != null 
                ? mSSLSocketFactory 
                : SSLSocketFactory.getSocketFactory(), 
                443));
    
        return new SingleClientConnManager(getParams(), registry);
    }
    
       MyHttpClient httpClient = new MyHttpClient();
    
        // set http params
        HttpParams params = httpClient.getParams();
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(30000));
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(30000));
        httpClient.setParams(params);
    
        ....
        httpClient.execute(httpUriRequest) 
    

提交回复
热议问题