2016-03-05 191 views
1

我設置了連接超時和讀取超時但仍然被忽略,請求只是永遠保持。如何設置超時,以便在達到超時時請求被取消? 這是我的代碼片斷,感謝您的幫助。HttpURLConnection連接超時不起作用

 urlConnection = (HttpURLConnection) saveURL.openConnection(); 
     // is output buffer writer 
     urlConnection.setRequestMethod("POST"); 
     urlConnection.setRequestProperty("Content-Type", "text/html"); 
     urlConnection.setRequestProperty("userid", id); 

     urlConnection.setConnectTimeout(3000); 
     urlConnection.setReadTimeout(3000); 
     urlConnection.setDoInput(true); 
     urlConnection.setDoOutput(true); 
     urlConnection.setUseCaches(false); 

     Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8")); 
     writer.write(jsonString); 
     writer.flush(); 
     // json data 
     writer.close(); 

     is = new BufferedInputStream(urlConnection.getInputStream()); 
     BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
     String inputLine = ""; 
     while ((inputLine = br.readLine()) != null) { 
      sb.append(inputLine); 
     } 

     int responseCode = urlConnection.getResponseCode(); 

    } catch (MalformedURLException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (ProtocolException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (UnsupportedEncodingException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (SocketTimeoutException soce) { 
     // TODO Auto-generated catch block 
     soce.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } finally { 

     try { 
      if (null != urlConnection) 
       urlConnection.disconnect(); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
+0

你怎麼知道它不工作? –

+0

因爲我設置了10秒的超時時間並對其進行計時。它持續了2分鐘以上,終於成功了。但問題是我已經看到它持續超過5分鐘,仍然沒有超時。我需要正常處理超時,以便用戶可以在網速更好時再次嘗試上傳。 –

+0

我只是說你似乎沒有回報什麼? –

回答

0

我不知道這是否是最好的選擇,我所做的就是要設置的我用來做切斷對HttpURLConnection的一次時間爲一個定時器。它似乎迄今工作正常。如果有人能指出這種方法的缺點並提出更好的方法,我將不勝感激。