Stopping silent retries in HttpURLConnection

后端 未结 4 2585
独厮守ぢ
独厮守ぢ 2021-02-20 16:50

I\'m using HttpURLConnection on Android KitKat to POST some data to a server. The server takes a long time to respond, and the connection is silently retry

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-20 17:39

    • Implement a hard timeout yourself, and force close the HttpURLConnection by calling disconnect. This can be done from your Activity using android handler; If you use AsyncTask, you can simply call cancel or Thread.interrupt():

      new Handler().postDelayed(new Runnable() {
          public void run() {
              httpUrlConnTask.cancel(true);
          }
      }, timeout * 1000); 
      

      And in your httpUrlConnTask, call disconnect:

      if (isCancelled()) {
          urlConnection.disconnect();
          return;
      }
      

      You may have to do urlConnection in another internal child thread so you can do a while loop in asynctask monitoring for isCancelled. And a try..catch so you can close all the streams properly.

    • you already have keepAlive false, and readTimeout, consider adding connection timeout too. This will set the socket timeout.

提交回复
热议问题