2013-09-27 63 views
0

目的使用HttpURLConnectionAsyncTask當我取消AsyncTask,並要求中止或取消AsyncTask採空連接好,但HttpURLConnection仍然發送請求,並與值從服務器android HttpURLConnection不會斷開?

回到我怎麼可以讓HttpURLConnection句號取消所有請求或中止請求?

這是代碼我使用

public static String post_string(String url, String urlParameters) throws IOException 
    { 

     HttpURLConnection conn = null; 

     try { 
       conn = (HttpURLConnection) new URL(url).openConnection(); 
      } catch (MalformedURLException e) { 
      Log.e(Logger, "MalformedURLException While Creating URL Connection - " + e.getMessage()); 
      throw e; 
      } catch (IOException e) { 
       Log.e(Logger, "IOException While Creating URL Connection - " + e.getMessage()); 
      throw e; 
      } 

     conn.setDoOutput(true); 

     conn.addRequestProperty("User-Agent", "Mozilla/5.0"); 
     conn.setRequestProperty("Accept-Charset", "UTF-8"); 
     conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
     //if has Post inputs 
     conn.setRequestProperty("Content-Length", Integer.toString(urlParameters.length()));  

     OutputStream os = null; 
     System.setProperty("http.keepAlive", "false"); 

     try { 
      os = conn.getOutputStream(); 
     } catch (IOException e) { 
     Log.e(Logger, "IOException While Creating URL OutputStream - " + e.getMessage()); 
     throw e; 
     } 
     try { 
      os.write(urlParameters.toString().getBytes()); 

     } catch (IOException e) { 
     Log.e(Logger, "IOException While writting URL OutputStream - " + e.getMessage()); 
     throw e; 
     } 
     InputStream in = null; 
     try { 
      in = conn.getInputStream(); 
     } catch (IOException e) { 
     Log.e(Logger, "IOException While Creating URL InputStream - " + e.getMessage()); 
     throw e; 
     } 
     String output = null; 
     try { 
      output = slurp(in); 
     } catch (IOException e) { 
      Log.e(Logger, "IOException While Reading URL OutputStream - " + e.getMessage()); 
      throw e; 
     } finally { 
     try { 
      os.close(); 
      in.close(); 
      } catch (IOException e) { 
      Log.e(Logger, "IOException While Closing URL Output and Input Stream - " + e.getMessage()); 
     } 
     } 
     conn.disconnect(); 

     Log.i("Server output " , output); 
     return output; 
    } 
    private static String slurp(InputStream in) throws IOException 
     { 
      StringBuffer out = new StringBuffer(); 

      byte[] b = new byte[4096]; 

       for (int n; (n = in.read(b)) != -1;) { 

       out.append(new String(b, 0, n)); 

      } 

      return out.toString(); 
    } 

,這是我用中止連接

conn.disconnect(); 

任何意見如何終止?

回答

1

當您停止AsyncTaskmTask.cancel(true);就叫conn.disconnect();

+0

我沒有,但在康涅狄格州還是工作!它返回從服務器的值也將其信息發佈到服務器,這是真的很奇怪 –

+0

你調試嗎?斷開連接後沒有插座打開,並確保沒有數據從服務器返回,發佈所有相關的代碼 –

+0

是的,我沒有調試它和LogCat打印服務器返回信息後,我斷開連接!劑量發生這是因爲使用'slurp(InputStream in)'的目標? –