[英]Single URLConnection to fetch only the first line in java using BufferedReader
我正在嘗試編寫一個Java程序,當且僅當更新時,該程序才應自動從網站下載文本。 我遇到的問題是僅使用一個HTTPURLConnection來執行此操作,因為如果不這樣做,由於使用了while(true)循環,將有數十億個HTTPURLConnections到達Web服務器。 這是我正在進行的工作,getMsg()方法接收一個URL並打開一個HTTPURLConnection。 目前,每次必須讀取一行時,我都會開始一個新的連接,這不是我確定的最有效的方法。 如何繼續使用相同的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;
}
}
為什么不簡單地在while循環之外聲明HttpURLConnection對象? 這樣,它將不會在循環內的每次調用時打開連接。
HttpURLConnection
無法重用,但是可以通過設置標頭Connection: keep-alive
在內部重用到同一服務器的打開連接。 顯然,如果您連接到其他服務器,這沒有任何意義。
一種有效測試是否存在更改的方法是使用If-Modified-Since
標頭或類似的If-Unmodified-Since
, If-None-Match
或If-Match
(請參閱HTTP標頭 )。 在這種情況下,如果有更改,則Web服務器決定傳遞新文檔,或者只是發送沒有正文的響應代碼304 Not Modified
。
關於成員(尤其是靜態成員)的使用的最后一件事:我將重構此代碼,並且唯一會保留為靜態的項是static void main()
。 您可以將靜態成員視為某種全局變量。 觀察到諸如“連接返回相同的消息”之類的內容,可能是對不當異常處理和靜態成員使用的影響。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.