我想製作一個簡單的Android應用程序,可以從網站(https://www.lottostat.dk/rssfeed.php)檢索彩票號碼。我嘗試使用此處提供的示例代碼(並在下面插入):Using Java to pull data from a webpage?無法從java/Android Studio中的網站獲取數據
示例代碼在使用原始目標網站(Using Java to pull data from a webpage?)時效果很好,並且我可以讀取Android Studio輸出中的整個底層html代碼。但是,當我將目標網站更改爲我想從中獲取數據的那個(https://www.lottostat.dk/rssfeed.php)時,沒有輸出(br.readLine()返回null)。
這裏有什麼問題?我是否需要一個不同的解決方案來閱讀.php網站(儘管底層代碼似乎是簡單的XML)?
下面是參考工作原始樣品代碼:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class DownloadPage {
public static void main(String[] args) throws IOException {
// Make a URL to the web page
URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");
// Get the input stream through URL Connection
URLConnection con = url.openConnection();
InputStream is =con.getInputStream();
// Once you have the Input Stream, it's just plain old Java IO stuff.
// For this case, since you are interested in getting plain-text web page
// I'll use a reader and output the text content to System.out.
// For binary content, it's better to directly read the bytes from stream and write
// to the target file.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
// read each line and write to System.out
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
謝謝!當我指定用戶代理程序代理時,它會工作。如何將用戶代理程序設置爲例如Mozilla是必要的? – daniel
@daniel如果您無法訪問服務器,我想不會有辦法。我建議你在這種情況下使用像Fiddler這樣的軟件:當在瀏覽器中顯示數據時,它應該會顯示,但在應用程序中什麼也沒有;然後,您捕獲請求到服務器,返回數據,比較應用程序發出的請求,並找出差異。 –
但它通常不會傷害指定用戶代理。或者您檢查內容是否返回空白,然後重試用戶代理。 –