Solved async request

Discussion in 'Spigot Plugin Development' started by mmuziek, Jul 28, 2018.

Thread Status:
Not open for further replies.
  1. hey there
    i normally find the problem solutions but this time im stuck.

    i almost never use http requests in my plugins.
    but i use a SDonate donation system which is a bit autdated but still works fine.
    Except for the lag on checking the server.
    When that happens the tps drops to 0 for 2 seconds.

    i found out that i think its not running async. can someone help me with this i have no idea how to do that as its not my direction of work.
    Thanks in advance.
    Here is the code that does the receiving of the data:
    Code (Java):
     public static String get(String url)
        throws Exception
      {
        URL oracle = new URL(url);
        URLConnection connection = oracle.openConnection();
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
        connection.connect();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        String websiteContent = "";
        while ((inputLine = in.readLine()) != null)
        {
         
          websiteContent = websiteContent + inputLine;
        }
        in.close();
        return websiteContent;
      }
    if someone can point me in the right direction or help me it would be awesome!
     
  2. If you don’t call that method aSync, it will be running on the main thread. Use aSync or use a callback for this
     
  3. Benz56

    Moderator Supporter

    Callback:
    Code (Java):
    public interface Callback {
      void onRetrieve(String result);
    }
    Wrap your code in an async task.
    Code (Java):
    public static void get(String url, Callback callback) {
        Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
            //Your code
            Bukkit.getScheduler.runTask(plugin, () -> callback.onRetrieve(websiteContent));
        });
    }
    //How to call
    Code (Java):
    YourClass.get(url, result -> {
      //Result is the retrieved websiteContent
    });
    Written on Spigot. Might contain a few typos or syntax errors. Your IDE should fix those.
     
  4. im testing it as we speak i will let you know!
     
  5. If that's all you're going to be doing, use a Consumer.
     
    • Agree Agree x 1
  6. it works without errors i need to test further ingame to see if it still lags
     
  7. Benz56

    Moderator Supporter

    Yea, that would do the trick as well.

    It won’t lag.
     
  8. it works perfectly!
    thanks for all help Topic solved!
     
Thread Status:
Not open for further replies.