How to stop HttpURLConnection connect on Android

前端 未结 2 1997
我寻月下人不归
我寻月下人不归 2020-12-01 15:07

I use AsyncTask to connect an URLPath as below code.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
           


        
相关标签:
2条回答
  • 2020-12-01 15:24

    Save the HttpURLConnection response by (HttpURLConnection)url.openConnection(); as a class member: HttpURLConnection mHttpURLConnection = (HttpURLConnection)url.openConnection();

    after you call future.cancel(true); then call mHttpURLConnection.disconnect()

    so the network request will end as fast as possible

    0 讨论(0)
  • 2020-12-01 15:36

    Wrap the code that uses HttpURLConnection inside a Future, which you can cancel at will. You can also use the Future's timeout feature, since the timeouts in HttpURLConnection are not reliable.

    Define an executor and future within your networking class:

    final ExecutorService executor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
    Future<MyResult> future;
    

    Then wrap your networking code inside the Future like this:

    future = executor.submit(new Callable<MyResult>() {
        @Override
        public MyResult call() throws IOException {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            try {
                // .. use the connection ...
            } finally {
                connection.disconnect();
            }
        }
    });
    
    MyResult result = future.get(TIMEOUT, TimeUnit.SECONDS);
    

    When you want to cancel, you can make this call from any thread:

    future.cancel(true);
    

    If the future times out or is canceled, the connection task may continue to block on a HttpURLConnection method, but your application won't be held back. You should still set appropriate timeouts on the connection to speed up freeing of threads and network sockets.

    0 讨论(0)
提交回复
热议问题