我尝试使用Unirest.get(...).asObjectAsync(...)
. 要停止使用 Unirest 的程序,您需要调用Unirest.shutdown();
以退出其事件循环和客户端。但是,如果某些线程在成功关闭后调用 Unirest 的请求方法,则程序无法退出。
以下代码是一个非常简单的示例:我启动一个线程,它在 1.5 秒后执行 GET 请求,并在成功时打印状态消息。同时在主线程上,Unirest 被关闭。(请注意,这个使用的示例asStringAsync(...)
和一个非常简单的线程为简单起见。)
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.async.Callback;
import com.mashape.unirest.http.exceptions.UnirestException;
import java.io.IOException;
public class Main {
public static void main(String... args) throws IOException, InterruptedException {
new Thread(() -> {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Unirest.get("http://example.org").asStringAsync(new Callback<String>() {
@Override
public void completed(HttpResponse<String> response) {
System.out.println(response.getStatusText());
}
@Override
public void failed(UnirestException e) {
System.out.println("failed");
}
@Override
public void cancelled() {
System.out.println("cancelled");
}
});
}).start();
Unirest.shutdown();
}
}
我所期望的是以下任何一种情况:
- 程序关闭,没有输出。
- 程序关闭,我得到以下任何输出:状态消息,失败或取消。
- 程序关闭但抛出异常,因为当 GET 请求发生时 Unirest 已经关闭。
我得到了什么:
- 程序没有关闭,GET 请求成功,打印“OK”。
我如何处理 Unirest 的优雅退出?我应该重组程序(如果是,如何重组)?
我在 Windows 上使用 Java 8,在 IntelliJ Idea 14.1.5 中运行代码。我使用的唯一依赖是:
<dependency>
<groupId>com.mashape.unirest</groupId>
<artifactId>unirest-java</artifactId>
<version>1.4.7</version>
</dependency>