我的Web服务在一个Thread的循环中调用代码。我使用不同的参数构建URL,并使用HttpURLConnection调用WS,如下所示:
public void run() {
//establish connection to db in another class
while(true) {
//Get args value from another class
for(String arg : args) {
try {
String invokeWS = "URL is built here with encoded args";
URL obj = new URL(invokeWS);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
con.disconnect();
System.out.println(response.toString());
} catch (UnsupportedEncodingException e) {
System.out.println("Unsupported Encoding Exception");
} catch (MalformedURLException e) {
System.out.println("Malformed URL Exception");
} catch (IOException e) {
System.out.println("IO Exception");
}
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("Interrupted Exception");
}
}
}
但是,如果在发送'GET'之后并且在接收到响应之前网络连接丢失,则控制永远不会返回到循环中的线程。我在这做错了什么?
避免在runnable中循环。我面临同样的问题,我减少了我的循环。我直接加载数据,然后循环我的最终侧可运行任务。