duanre4421 2011-03-24 18:36
浏览 178
已采纳

Java - 从PHP网页URL读取txt文件

First of all, I'm a newbie to Java and my English is bad, so hope you can understand my problem.

I want to read the text file from this URL: http://www.cophieu68.com/export/metastock.php?id=AAA

Okay, let me explain. This is a Vietnamese stock data website and the link above point to the file aaa.txt which contains the information of the stock with codename is AAA. And I can take the other stocks info by just modifying the value of the id variable.

And my problem is what I get is a bunch of HTML code, not the text file I expect (aaa.txt)

And here is my code:

    public static void main(String[] args){
    try {

        URL url = new URL("http://www.cophieu68.com/export/metastock.php?id=AAA");
        URLConnection urlConn = url.openConnection();

        System.out.println(urlConn.getContentType());  //it returns text/html

        BufferedReader in = new BufferedReader
        (new InputStreamReader(urlConn.getInputStream()));

        String text;

        while ((text = in.readLine()) != null) {

            System.out.println(text);
        }

        in.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Thanks for your help.

  • 写回答

2条回答 默认 最新

  • dtd793353 2011-03-24 18:55
    关注

    The site seems to be sniffing the user-agent to decide what content to send down.

    If you spoof the user-agent as shown below, it works as you'd expect - the response is the plain-text file:

    urlConn.setRequestProperty ( "User-agent", "Mozilla/5.0 (X11; U; Linux i686; pl-PL; rv:1.9.0.2) Gecko/20121223 Ubuntu/9.25 (jaunty) Firefox/3.8");

    As you can probably tell, this pretends that the user-agent is Firefox 3.8 on Ubuntu.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog