问题描述
我正在尝试编写一个Java程序,当且仅当更新时,该程序才应自动从网站下载文本.我遇到的问题是仅使用一个HTTPURLConnection来执行此操作,因为如果不这样做,由于使用了while(true)循环,将有数十亿个HTTPURLConnections到达Web服务器.这是我正在进行的工作,getMsg()方法接收一个URL并打开一个HTTPURLConnection.目前,每次必须读一行时,我都会开始一个新的连接,这不是我确定的最有效的方法.如何使用相同的HTTPURLConnection继续读取同一行?
I am trying to write a Java program that should automatically download text from a website if and only if it gets updated. The problem I am running into is using only one HTTPURLConnection to do that because if i don't there will be billions of HTTPURLConnections to the web server since I am using a while(true) loop. Here is my work-in-progress, the getMsg() method receives a url and opens an HTTPURLConnection. Currently I am starting a new connection every time I have to read a line, which is not the most efficient way I am sure. How do I keep reading the same line with the same HTTPURLConnection?
// Starts a new URLConnection to "localhost/currentmsg.dat"
// Receives JSON string from the URLConnection
// Sets up a different variable for each object received from the URL for eg. if delete=1 means that the admin is requesting to delete a message from the screen.
import java.io.*;
import java.net.*;
import org.json.*;
import java.io.*;
import java.util.Scanner;
public class jListenerURL {
// Current arguments retrieved from the URL
private static int msgID = 0;
private static int aptID = 1; // Apartment ID of current device
private static int unitID = 3; // Unit ID of current device
static String message; // Message received from admin
static int delete; // Delete a message?
static int dmsgID; // What message to delete?
public static void jListener() {
URL url;
boolean keepGoing = true;
String msg = "";
try {
url = new URL("http://www.lotussmoke.com/msgtest/currentmsg.dat");
while (keepGoing) {
msg = getMsg(url);
JSONObject jObj = null;
try {
jObj = new JSONObject(msg);
}
catch (JSONException je) {
System.out.println("JSON Exception for message, try restarting terminal.");
}
int current = jObj.getInt("msgID");
int targetaptID = jObj.getInt("aptID");
int targetunitID = jObj.getInt("unitID");
// Keep listening, if the message changes meaning a different msgID then print that message
if (current!=msgID && targetaptID == aptID && targetunitID == unitID) {
msgID = jObj.getInt("msgID");
message = jObj.getString("message");
delete = jObj.getInt("delete");
dmsgID = jObj.getInt("dmsgID");
if (delete==1) {
// Delete a message
System.out.println("Delete msg ID? " + dmsgID);
continue;
}
System.out.println("Message ID: " + msgID);
System.out.println("Apartment ID: " + aptID);
System.out.println("Unit ID: " + unitID);
System.out.println("Message: " + message);
}
}
}
catch (MalformedURLException e) {
System.err.println();
}
}
public static void main(String args[]) throws Exception {
jListener();
}
private static String getMsg(URL url) {
HttpURLConnection con = null;
try {
con = (HttpURLConnection) url.openConnection();
} catch (IOException e1) {
e1.printStackTrace();
}
BufferedReader in = null;
String msg = "";
try {
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String received;
while((received = in.readLine()) != null) {
//System.out.println(received);
msg = received;
}
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
return msg;
}
}
推荐答案
HttpURLConnection
无法重用,但是它可以通过设置标头Connection: keep-alive
在内部重用与同一服务器的开放连接.显然,如果您连接到其他服务器,这是没有意义的.
HttpURLConnection
cannot be reused, but it can reuse an open connection to the same server internally by setting the header Connection: keep-alive
. It doesn't make sense if you connect to different servers, obviously.
一种有效测试是否存在更改的方法是使用If-Modified-Since
标头或类似的If-Unmodified-Since
,If-None-Match
或If-Match
(请参见 HTTP标头).在这种情况下,如果有更改,则Web服务器决定发送新文档,或者只是发送没有正文的响应代码304 Not Modified
.
One way to efficiently test whether there are changes, is to use If-Modified-Since
header or the like If-Unmodified-Since
, If-None-Match
or If-Match
(see HTTP Headers). In this case the web-server decides to deliver a new document if there are changes or just sends the response code 304 Not Modified
without a body.
关于成员(尤其是静态成员)的使用的最后一件事:我将重构此代码,而剩下的唯一静态元素是static void main()
.您可以将静态成员视为某种全局变量.观察到诸如连接返回同一条消息"之类的内容,可能是对异常处理和静态成员的使用不当造成的.
One last thing regarding the use of members (and especially static members): I'd refactor this code and the only item which would be left as static is static void main()
. You can see the static members as some kind of global variables. Observing something like 'the connection is returning the same message' might be a effect of inappropriate exception handling and usage of static members.
这篇关于单个URLConnection使用BufferedReader仅获取Java中的第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!