0

当我取消并请求中止或取消连接时,瞄准使用HttpURLConnection内部停止好的,但仍然发送请求并返回来自服务器的值AsyncTaskAsyncTaskAsyncTaskHttpURLConnection

我怎样才能使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(); 

任何建议如何中止?

4

1 回答 1

1

当你停止AsyncTask喜欢 的时候mTask.cancel(true);就打电话conn.disconnect();

于 2013-09-27T09:38:25.557 回答