2013-09-27 41 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)'的目标? –