[英]Get page source using Java is reading only 1st line
我一生中從未使用過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&A for professional and enthusiast programmers" /> <meta name="og:url" content="http://stackoverflow.com/"/>
嘗試使用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");
?>
如果還是不行,請以空字符串初始化變量內容 ,以防萬一。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.