-
Notifications
You must be signed in to change notification settings - Fork 9.2k
Closed
Description
The Recipes Canceling a Call worked, but after I used OkHttpClient.cancel(tag)
instead, it didn't work.
My code:
import java.io.IOException;
import java.util.concurrent.*;
import com.squareup.okhttp.*;
public class Test {
private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay.
.tag("asdf")
.build();
final long startNanos = System.nanoTime();
final Call call = client.newCall(request);
// Schedule a job to cancel the call in 1 second.
executor.schedule(new Runnable() {
@Override public void run() {
System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f);
client.cancel("asdf");
System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f);
}
}, 1, TimeUnit.SECONDS);
try {
System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f);
Response response = call.execute();
System.out.printf("%.2f Call was expected to fail, but completed: %s%n",
(System.nanoTime() - startNanos) / 1e9f, response);
} catch (IOException e) {
System.out.printf("%.2f Call failed as expected: %s%n",
(System.nanoTime() - startNanos) / 1e9f, e);
}
}
public static void main(String[] args) throws Exception {
new Test().run();
}
}
Result:
0.25 Executing call.
1.25 Canceling call.
1.25 Canceled call.
3.46 Call was expected to fail, but completed: Response{protocol=http/1.1, code=200, message=OK, url=http://httpbin.org/delay/2}
Metadata
Metadata
Assignees
Labels
bugBug in existing codeBug in existing code