gpt4 book ai didi

java - unirest shutdown 退出程序

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:57:28 31 4
gpt4 key购买 nike

我尝试使用 Unirest.get(...).asObjectAsync(...) 使用计划任务更新资源。要停止使用 Unirest 的程序,您需要调用 Unirest.shutdown(); 以退出其事件循环和客户端。但是,如果某些线程在成功关闭后调用了Unirest的request方法,程序将无法退出。

以下代码是一个非常简单的示例:我启动了一个线程,该线程在 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 中运行代码。我使用的 unirest 依赖是:

<dependency>
<groupId>com.mashape.unirest</groupId>
<artifactId>unirest-java</artifactId>
<version>1.4.7</version>
</dependency>

最佳答案

在您的例子中,您生成了一个运行异步调用的线程。 shutdown() 调用在您的主线程中,因此在调用线程产生时,shutdown() 将在 之前被调用可以先调用Unirest的asStringAsync()方法。

这是对实例化最终需要关闭的线程池的 ..Async() 的第一次调用 - 在您调用关闭时没有任何东西可以关闭方法,所以它是一个空操作。它将在您创建的线程中实例化。

这里的解决方案是删除您创建的线程,并使用 Unirest 为您提供的 Future 对象。当您进行异步调用时,Unirest 会自行处理线程,您可以根据需要输入回调逻辑。

    public static void main(String... args) throws IOException, InterruptedException, ExecutionException {
Future<HttpResponse<String>> asyncCall = Unirest.get("http://thecatapi.com/api/images/get?format=xml&results_per_page=20").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");
}
});
HttpResponse<String> httpResponse = asyncCall.get(); // Can also use Future.isDone(), etc
// System.out.println(httpResponse.getBody());
Unirest.shutdown();
}

关于java - unirest shutdown 退出程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32873070/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com