1

我正在通过 servlet 和 db 处理程序 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.

这是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().

我认为问题是由于类变量conn,并且在浏览器中重新加载没有被复制..

知道怎么做吗?

4

1 回答 1

3

您基本上只连接(请求)一次并尝试多次读取响应,而它只能读取一次。您基本上每次都需要创建一个新的连接(请求)。您需要将连接的创建移动url.openConnection()到循环内部。顺便说一句,这条线http.connect()是多余的。您可以放心地忽略它。http.getInputStream()意志已经隐含地做到了。

也可以看看:

于 2013-01-12T14:38:32.407 回答