Solved Http request in async thread?

Discussion in 'Spigot Plugin Development' started by mindgamesnl, Apr 13, 2017.

  1. Hey guys!

    I'm running in to a problem where a http request couses a huge lag spike in the server.

    One of the solutions i can come up with is running it in the async thread, but how?

    My main problem is failing to return a string from async (only tried Bukkit scheduler)

    Thanks :)

    My current code is:
    Code (Java):

    public static String textFromUrl(String request) throws IOException {
            URL url;
            url = new URL(request);
           BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
           String str;
           while ((str = in.readLine()) != null) {
             return str;
            return str;
  2. You could pass a Consumer<String> to the method to specify what code to run once the task has finished, then call the consumer sync.
  3. How to implement that? (sorry but i don't understand)
  4. There is "I use Java 7" paragraph in this thread exactly for the people like you. There is no reason to not use Java 8 now. Nothing will break if you will just update your JDK and server JRE from 7 to 8 because Java have strong backwards compatibility.
    • Agree Agree x 1
  5. Oh awesome!

    Gonna play around with it, thanks!