简体   繁体   English

如何在 Java 中发出异步 http get 请求?

[英]How do I make async http get requests in Java?

I wrote a program where I call many http get request.我写了一个程序,我调用了许多 http get 请求。 It takes like half a minute till all the get requests are done but it needs to be done within a second, this can be achieved with calling this method asynchronously, right?完成所有的get请求需要半分钟,但需要在一秒钟内完成,这可以通过异步调用这个方法来实现,对吧? But how?但是怎么办?

This is what my get request looks like:这是我的获取请求的样子:

public static String dataRequest(String link) throws IOException {
    URL url = new URL(link);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/json");
    if (conn.getResponseCode() != 200) {
        throw new RuntimeException("Failed : HTTP Error code : " + conn.getResponseCode());
    }
    InputStreamReader in = new InputStreamReader(conn.getInputStream());
    BufferedReader br = new BufferedReader(in);
    String output;
    String result = "";
    while ((output = br.readLine()) != null) {
        result += output;
    }
    conn.disconnect();
    return result;
}

I tried using RxJava but I couldn't get it to work at all.我尝试使用 RxJava,但我根本无法让它工作。 I'm in a Maven JavaFx project.我在一个 Maven JavaFx 项目中。 This method is in my getData class.这个方法在我的getData class中。

You can try using thread with ForkJoinPool您可以尝试将线程与 ForkJoinPool 一起使用

For example -> https://www.baeldung.com/java-fork-join例如 -> https://www.baeldung.com/java-fork-join

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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