【问题标题】:Get page source using Java is reading only 1st line使用 Java 获取页面源代码仅读取第一行
【发布时间】:2013-10-01 07:32:18
【问题描述】:

我这辈子从来没有用过java,但是我很擅长php,我想获得一个网站的页面源。但我正在使用Appspot(GAE)。file_get_contents和Curl不起作用。所以我想要通过java获取页面源。我学习了一些java基础知识并在下面找到了代码,但是下面的代码只得到了外部页面的第一行。请指导我哪里错了。

<?php

function get($url){

        import java.net.URL;
        import java.io.BufferedReader;
        import java.io.InputStreamReader;

        $java_url = new URL($url);
        $java_bufferreader = new BufferedReader(new InputStreamReader($java_url->openStream()));

        while (($line = $java_bufferreader->readLine()) != null) {
            $content .= $line;
        }

        return $content;
}


echo get("http://domain.com");

?>

例如,如果我抓取 stackoverflow.com,它只返回以下代码

<!DOCTYPE html><html><head>        <title>Stack Overflow</title>    <link rel="shortcut icon" href="//cdn.sstatic.net/stackoverflow/img/favicon.ico">    <link rel="apple-touch-icon image_src" href="//cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png">    <link rel="search" type="application/opensearchdescription+xml" title="Stack Overflow" href="/opensearch.xml">    <meta name="twitter:card" content="summary">    <meta name="twitter:domain" content="stackoverflow.com"/>    <meta name="og:type" content="website" />    <meta name="og:image" content="http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon@2.png?v=fde65a5a78c6"/>    <meta name="og:title" content="Stack Overflow" />    <meta name="og:description" content="Q&amp;A for professional and enthusiast programmers" />    <meta name="og:url" content="http://stackoverflow.com/"/>

【问题讨论】:

  • 你是什么意思 file_get_contents 不工作?它适用于在 GAE PHP 中读取 http 流。
  • 我没有使用官方的 GAE php

标签: java php google-app-engine


【解决方案1】:

尝试使用 Scanner 类。

<?php

function get($url){

        import java.net.URL;
        import java.util.Scanner;

        $java_url = new URL($url);
        $java_scanner = new Scanner($java_url->openStream());

        while (($line = $java_scanner->nextLine()) != null) {
            $content .= $line;
        }

        return $content;
}


echo get("http://domain.com");

?>

如果这也不起作用,请使用空字符串初始化变量 content,以防万一。 :)

【讨论】:

  • 你能把$content = '';放在导入行之后然后这样试试吗?
  • 我认为当该行为 null 时它会停止,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多