2012-11-20 120 views
5
public class UrlVarificationTask extends AsyncTask<Void, Void, Integer> { 

    private String url; 
    private UrlVarificationDelegate delegate; 
    private HttpURLConnection huc; 

    public UrlVarificationTask(String url, UrlVarificationDelegate delegate) { 
     this.url = url; 
     this.delegate = delegate; 
    } 

    @Override 
    protected void onPreExecute() { 

     super.onPreExecute(); 
    } 

    @Override 
    protected Integer doInBackground(Void... params) { 
     int responseCode = 0; 
     try { 
      System.setProperty("http.keepAlive", "false"); 
      URL u = new URL(url); 
      huc = (HttpURLConnection) u.openConnection(); 
      huc.setRequestMethod("HEAD"); 
      huc.connect(); 
      responseCode = huc.getResponseCode(); 

     } catch (MalformedURLException mal) { 
      responseCode = -555; 
     } catch (IOException io) { 
      responseCode = -444; 
     } catch (Exception ex) { 
      responseCode = -333; 
      ex.printStackTrace(); 
     } 

     if (huc != null) { 
      try { 
       huc.getInputStream().close(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      huc.disconnect(); 
     } 

     Logger.debug("Response Code==" + responseCode); 
     return responseCode; 
    } 

    @Override 
    protected void onPostExecute(Integer responseCode) { 
     delegate.urlVarificationResponseCode(responseCode); 
     super.onPostExecute(responseCode); 
    } 

} 

我上面核桃用於驗證網址,URL驗證工作正常,但保持連接,並限制任何進一步的請求

如果HEAD給我響應代碼200只,然後我打開一個URL網頁視圖。

但是一旦我調用它,它保持連接並且不允許任何其他的http請求,即使關閉後,該怎麼辦?

Safe use of HttpURLConnection

回答

4
huc.setRequestProperty("keep-alive", "false"); 

這是工作爲HttpURLConnection的保持連接,因此我們水溼讓做進一步的請求,從而保持活動設置爲false解決這個問題。

1

對於正常關閉HttpURLConnection轉到link

通過這個URL被關閉。

相關問題