setConnectTimeout对android没有影响

时间:2012-04-24 19:08:42

标签: android settimeout httpurlconnection

我正在尝试setConnectTimeout,但它似乎没有任何效果。

这是我的代码:

    URL url = null;
    URLConnection uc =  null;
    HttpURLConnection  connection = null;
    int TIMEOUT = 4000;
    System.setProperty("http.keepAlive", "false");

    try{
        url = new URL(targetURL);
        uc =  url.openConnection();
        connection = (HttpURLConnection )uc;

        connection.setConnectTimeout(TIMEOUT);
        connection.setReadTimeout(TIMEOUT);
        connection.setDoInput(true);
        connection.setDoOutput(true);


        //get response               
        String  response = "";
        InputStream instream = null;    

         try{            
             String rep = connection.getResponseMessage();
             int respcode = connection.getResponseCode();        
             response = respcode+"";

             Log.i("Server Response", ""+respcode+": "+rep);

             //get XML from InputStream
            if(connection.getResponseCode() == 200){
                connection.connect();       
                instream = connection.getInputStream();     
                buildDoc(instream);     
            }
            else{
                instream = connection.getErrorStream();
            }

            parse_status= true;

        }catch(Exception e){
            Log.e(TAG,"Unable to create connection stream");
            parse_status= false;
            e.printStackTrace();
        }
         finally {      
          if(instream != null) {
            Log.i(TAG,"Disconnecting stream");
            try {
                instream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
          }
         }


    }catch(SocketTimeoutException e){
        Log.e(TAG,"Unable to create connection");
        e.printStackTrace();
        parse_status= false;
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally {      
          if(connection != null) {
            Log.i(TAG,"Disconnecting");
            connection.disconnect(); 
          }
    }

    return parse_status;
}

0 个答案:

没有答案