Closing an HttpURLConnection before the response is complete

后端 未结 3 1608
春和景丽
春和景丽 2021-01-18 10:36

Background

I\'m using HttpURLConnection on the client side to consume a response in an HTTP streaming (server push) situation. Although the server may close the co

3条回答
  •  萌比男神i
    2021-01-18 11:30

    If server does not close connection but stops sending data, in.read() will block. Now, notice that the code for HttpURLConnection.HttpInputStream.close() will attempt to read from the stream as well to determine that end of stream is reached (source code). close(), in turn, is called from disconnect(). And you end up with your threads blocked.

    So it appears that you need to alter your logic. I assume that you close connection based on some conditions. So instead of doing it in different thread check for conditions before reading next byte in the reading thread and then do disconnect.

    And, by the way, Thread.interrupt() is not going to help you as it will only interrupt threads waiting on monitors while yours is waiting on IO.

提交回复
热议问题