我正在努力创建一个监视web api的线程,以通过JSON获取最新的声明。我目前无法对此进行测试,因此我不确定是否需要更改此内容。我已经阅读了其他问题,但其他人似乎都没有使用循环来继续得到回复。
public void run(){
try {
URL url = new URL(announcementsURL);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("GET");
http.setRequestProperty("Connection", "keep-alive");
http.setUseCaches(false);
http.setAllowUserInteraction(false);
http.setConnectTimeout(10);
http.setReadTimeout(10);
while (true){
http.connect();
int status = http.getResponseCode();
if (status == 201){
BufferedReader br = new BufferedReader(new InputStreamReader(http.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
String json = sb.toString();
JSONParser parser = new JSONParser();
JSONObject jsonResponse = (JSONObject) parser.parse(json);
if (!(lastAnnouncement == (long) jsonResponse.get("time"))){
//String announcement = (String) jsonResponse.get("message");
//TODO What to do with announcement...
}
}
http.getInputStream().close();
http.disconnect();
}
} catch (IOException | ParseException e) {
e.printStackTrace();
this.interrupt();
try {
this.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}