我正在通过一个 servlet 和一个数据库处理程序 java 类从数据库中获取一些数据,并将其托管在一个 url 上。由于数据库在变化,我只注意托管更改而不是整个数据库数据。
我正在通过浏览器获取所需的功能,即在每次(手动)重新加载后,我都会根据需要获取数据,
1. at the first page load, entire data gets displayed.
2. at subsequent reloads, I get either null data if there is no change in the database, or the appended rows if the database extends. (the database can only extend).
但是在 java 程序中,我没有获得相同的功能。使用 HttpUrlConnection
的 java 程序。
这是 servlet 的 java 客户端代码...
public class HTTPClient implements Runnable {
private CallbackInterface callbackinterface;
private URL url;
private HttpURLConnection http;
private InputStream response;
private String previousMessage = "";
public HTTPClient() {
try {
url = new URL("http://localhost:8080/RESTful-Server/index.jsp");
http = (HttpURLConnection) url.openConnection();
http.connect();
} catch (IOException e) {
}
}
@Override
public void run() {
while (true) {
try {
String currentmessage = "";
response = http.getInputStream();
if (http.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader buffread = new BufferedReader(new InputStreamReader(response));
String line;
for (; (line = buffread.readLine()) != null;) {
currentmessage += line;
}
if ((!currentmessage.equals(previousMessage)
|| !previousMessage.equals(""))
&& !currentmessage.equals("")) {
//this.callbackinterface.event(currentmessage);\
System.out.println(currentmessage + "\t" + previousMessage);
}
previousMessage = currentmessage;
Thread.sleep(2500);
} else {
throw new IOException();
}
} catch (IOException | InterruptedException e) {
System.err.println("Exception" + e);
}
}
}
显示的类是一个线程,每 2.5 秒读取一次连接。如果它在 getline()
中获得了一些重要信息,它会向 worker 方法发出回调,该方法负责处理剩余的事情。
我认为问题是因为类变量 conn,并且没有像在浏览器中那样重新加载。
知道怎么做吗?
最佳答案
您基本上只连接(请求)一次并尝试多次读取响应,而它只能读取一次。您基本上每次都需要创建一个新连接(请求)。您需要将 url.openConnection()
的连接创建移动到循环内部。 http.connect()
行是多余的。您可以安全地忽略它。 http.getInputStream()
已经隐式执行了。
另见:
关于java - 最接近Java中网页重新加载的等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14294312/