有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

无法从java/Android Studio中的网站获取数据

我正在尝试制作一个简单的Android应用程序,可以从网站(https://www.lottostat.dk/rssfeed.php)检索彩票号码。我尝试过使用这里提供的示例代码(并在下面插入):Using Java to pull data from a webpage?

使用原始目标网站(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);
        }
    }
}

共 (2) 个答案

  1. # 1 楼答案

    添加一个用户代理,该代理应该可以做到这一点(在android 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();
    
  2. # 2 楼答案

    显然,这个网站依赖于用户代理。添加用户代理头可以解决这个问题。尝试使用

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