1

It looks like SocketChannel supports being interrupted, yet regular sockets do not.

Do any java HTTP clients exists which are able to use the SocketChannel instead of Socket.

I would like to support threads being interrupted when reading from the server, currently when using URL#openConnection() if the thread is stuck waiting for a response from the server it can not be unstuck by interrupting it.

Luke
  • 884
  • 8
  • 21
  • Maybe you could check this https://stackoverflow.com/questions/12383854/how-to-stop-httpurlconnection-connect-on-android/26489077#26489077 – VijayC Mar 18 '20 at 07:04
  • Usually the workaround is that Sockets can have timeouts set (connect timeout or data timeout), which raises IOExceptions when reached. Not quiete the same, but from what I recall, every major HTTP client library has those kind of settings. – GPI Mar 18 '20 at 09:12
  • @VijayC the suggestion in that answer is bad it assumes that interrupts work. – Luke Mar 19 '20 at 01:07

1 Answers1

2

I've never used it myself, but it looks like what would be closest to your need is a non-blocking HTTP client. The only implementation I know of is Netty based Spring reactive client: reactor-netty.

It should allow you to do something like this:

final Mono<HttpClientResponse> futureResponse = HttpClient.create()
           .baseUrl("http://example.com")
           .get()
           .response();

final Disposable httpHandle = response.subscribe(
    response -> onSuccess(response),
    response -> onError(response)
);

// When you want to force disconnection
httpHandle.dispose();

Note: be cautious however, because I'm really not aware of the limitations of this system. However, Spring team provides advanced documentation to help.

amanin
  • 3,436
  • 13
  • 17