我正在尝试向我的网络服务器发出http请求。这些HTTP请求的响应时间相当长。 Web服务器可能需要大约20秒才能回复。
我听说你可以在ASync线程中放置http请求,这样它们就不会挂起整个服务器20秒。
这是我的代码:
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;
}