title: Interrupt HttpURLConnection request Android
body: <p>I am creating simple class which sends requests using HttpURLConnection to server and receive responses. I want to add interrupt() method which interrupt current request (imagine request is running in AsyncTask and interrupt() is called from main thread). There are 2 processes which takes a lot of time and I don't know how to interrupt them: </p>
  
  <ul>
  <li>writing to output stream</li>
  <li>reading from input stream</li>
  </ul>
  
  <p>So let's say that I want to for example interrupt reading from input stream which I read like this:</p>
  
  <pre><code>downloadThread = new Thread(new Runnable() {
      @Override
      public void run() {
          try {
              buffer = readFully(connection.getInputStream());
          } catch( Exception e ) {
              e.printStackTrace();
          }
      }
  });
  downloadThread.start();
  </code></pre>
  
  <p>And readFully() method is:</p>
  
  <pre><code>public byte[] readFully(InputStream input) throws IOException {
      byte[] buffer = new byte[8192];
      int bytesRead;
      ByteArrayOutputStream output = new ByteArrayOutputStream();
      while ((bytesRead = input.read(buffer)) != -1) {
          output.write(buffer, 0, bytesRead);
      }
      return output.toByteArray();
  }
  </code></pre>
  
  <p>How can I stop reading from input stream (in other words, downloading) ?
  stop() method of Thread is deprecated and cannot be used. There are written everywhere that I should regularly check if thread should be stopped and stop it manually. But how can I do that when whole time takes this line (If I understand well):</p>
  
  <pre><code>connection.getInputStream()
  </code></pre>
  
  <p>I think this is the same kind of question but it is unanswered (see comments of solution):
  <a href="https://stackoverflow.com/questions/12383854/how-to-stop-httpurlconnection-connect-on-android">How to stop HttpURLConnection connect on Android</a>
  Please, don't refer me to some REST library. I would really like to know how to handle this issue. Thanks ;).</p>