【问题标题】:Can't get data from website in java/Android Studio [duplicate]无法从 java/Android Studio 中的网站获取数据 [重复]
【发布时间】:2016-12-19 15:25:41
【问题描述】:

我正在尝试制作一个简单的 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);
        }
    }
}

【问题讨论】:

    标签: java android


    【解决方案1】:

    显然,此网站依赖于用户代理。添加 User-Agent 标头可以解决问题。尝试使用

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

    【讨论】:

      【解决方案2】:

      添加一个用户代理,应该可以解决问题(使用 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();
      

      【讨论】:

      • 谢谢!它在我指定用户代理代理时起作用。如何知道是否将用户代理设置为例如Mozilla 有必要吗?
      • @daniel 如果您无权访问服务器,我想没有办法。在这种情况下,我建议您使用 Fiddler 之类的软件:当在浏览器中显示应有的数据但在应用程序中什么都没有时;然后你捕获到服务器的请求返回数据,与应用程序发出的比较并找出差异。
      • 但是指定一个用户代理通常没有坏处。或者您检查内容是否返回空,然后使用用户代理重试。
      猜你喜欢
      • 2019-10-17
      • 2015-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-28
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      相关资源
      最近更新 更多