简体   繁体   中英

Java HTTP client which uses SocketChannel so that I may interrupt threads reading a request

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM