我試圖打開我的大學網站來閱讀他們的菜單。我已經寫了一個版本,可以直接讀取菜單鏈接到菜單鏈接的菜單,但是我想將它拉回一點,以便從網站上讀取菜單,而不是直接鏈接(如果鏈接發生更改) 。網站不喜歡Java嗎?
這裏是我打開的網址: https://nccudining.sodexomyway.com/dining-choices/index.html
每當我打開鏈接的網站,這是我得到的輸出:
302
<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="http://m-nccudining.sodexomyway.com/dining-choices/index.html">here</a>.</h2>
</body></html>
它輸出的網址是移動版的網站,但當我嘗試使用該網址時,它不輸出任何內容。
這是我的代碼:
import java.io.*;
import java.net.*;
public class test
{
public static void main(String[] args)
{
URL url = null;
try
{
url = new URL("https://nccudining.sodexomyway.com/dining-choices/index.html");
HttpURLConnection test = (HttpURLConnection) url.openConnection();
test.setInstanceFollowRedirects(true);
test.connect();
System.out.println(test.getResponseCode());
} catch (MalformedURLException e1)
{
System.out.println("URL cannot be opened.");
return;
}
BufferedReader in = null;
try
{
in = new BufferedReader(new InputStreamReader(url.openStream()));
} catch (IOException e)
{
System.out.println("Error");
}
String inputLine;
try
{
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine);
}
} catch (IOException e)
{
System.out.println("Error");
}
}
}
我所有的try/catch循環道歉。我不想僅僅從一開始就拋出一個IOException異常,因爲我聽說這是不好的做法。無論如何,這段代碼只是打開URL,建立一個連接,所以我可以確保URL實際存在,並嘗試閱讀它的HTML。它適用於我嘗試過的任何其他網站,包括谷歌。
我的問題是爲什麼我的代碼不能讀取網站的正確源代碼?我的代碼有問題嗎(我想在HttpsURLConnection中添加並允許重定向會起作用),還是僅僅是網站,我有什麼可以繞開每週菜單的頁面來繞過這些?
找到解決方案!感謝@ShayHaned的修復。我添加下列行到HttpURLConnection類所以我得到一個200響應代碼,而不是302:
test = (HttpURLConnection) url.openConnection();
test.setRequestMethod("GET");
test.setRequestProperty("User-Agent", "Mozilla/5.0");
test.setInstanceFollowRedirects(true);
然後我從URL打開流從HttpURLConnection類獲取輸入流改變了的InputStream,如圖所示:
BufferedReader in = new BufferedReader(new InputStreamReader(test.getInputStream()));
這給了我正在尋找的HTML。
什麼是響應代碼?如果它不是301或類似的,問題出現在服務器端:它們不發佈重定向,所以Java沒有遵循。 – EJP
@EJP這就是他的第一個代碼塊...... –
它讀取網頁的HTML。現在,它沒有做任何事情,因爲我只是想解決這個問題。 – ds777fighter