0

I'm trying to make http requests to my web server. These HTTP requests have a fairly lengthy response time. It probably takes around 20 seconds for the web server to reply.

I've heard that you can put http requests in ASync threads so that they wont hang the entire server for 20 seconds.

Here is my code:

public String myFunction(Player player){
    String url = "http://domain.com/" + player.getName();
    String message = getJson(url);
    return message;
}   

public String getJson(String url){
        String msg;
        try {
            String URL = http(url);
            JsonObject jo = new Gson().fromJson(URL, JsonObject.class);
            if (jo.get("error").getAsInt() == 1) {
                return jo.get("message").getAsString();
            } else if (jo.get("error").getAsInt() == 0) {
                msg = jo.get("message").getAsString();
            } else {
                return "Fatal Error Occured (5)";
            }
        } catch (IOException e1) {
            e1.printStackTrace();
            return "Fatal Error Occured (6)";
        }
        return msg;
    }

    private String http(String string) throws IOException {
        String msg = "";
        URL obj = new URL(string);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", "MyAgent");
        BufferedReader in = new BufferedReader(
        new InputStreamReader(con.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            if (msg.length() == 0) {
                msg = line;
            } else {
                msg = msg + "\n" + line;
            }
        }
        in.close();
        return msg;
    }
Jojodmo
  • 23,357
  • 13
  • 65
  • 107
Toby Mellor
  • 8,093
  • 8
  • 34
  • 58

0 Answers0