2016-08-12 88 views
1

我想製作一個簡單的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); 
     } 
    } 
} 

回答

0

添加用戶代理,即應達到目的(與機器人5.1.1設備測試):

URL url = new URL("https://www.lottostat.dk/rssfeed.php"); 
URLConnection con = url.openConnection(); 
con.setRequestProperty("User-Agent", "Mozilla"); 

替代方法:使用jsoup

Document doc = Jsoup.connect("https://www.lottostat.dk/rssfeed.php").userAgent("Mozilla").get();   
String content = doc.toString(); 
+0

謝謝!當我指定用戶代理程序代理時,它會工作。如何將用戶代理程序設置爲例如Mozilla是必要的? – daniel

+0

@daniel如果您無法訪問服務器,我想不會有辦法。我建議你在這種情況下使用像Fiddler這樣的軟件:當在瀏覽器中顯示數據時,它應該會顯示,但在應用程序中什麼也沒有;然後,您捕獲請求到服務器,返回數據,比較應用程序發出的請求,並找出差異。 –

+0

但它通常不會傷害指定用戶代理。或者您檢查內容是否返回空白,然後重試用戶代理。 –

1

顯然,該網站是依賴於用戶代理的。添加User-Agent頭解決了這個問題。嘗試使用

URLConnection con = url.openConnection(); 
    con.setRequestProperty("User-Agent", "Mozilla/5.0"); 
    InputStream is =con.getInputStream();