我让webservice在线程中循环调用代码。我使用diffirent参数构建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中循环。我面临着同样的问题,我减少了循环。我加载了直接的数据,然后在我的末端外循环可运行的任务。