0

URLConnection を使用して Web ページのソースを取得しようとすると、奇妙な理由で出力に「null」が表示されます。誰でも光を当てることができますか?

私の方法:

public String getPageSource()
        throws IOException
{
    URL url = new URL( this.getUrl().contains( "http://" ) ? this.getUrl() : "http://" + this.getUrl() );
    URLConnection urlConnection = url.openConnection();

    BufferedReader br = new BufferedReader( new InputStreamReader( urlConnection.getInputStream(), "UTF-8" ) );

    String source = null;
    String line;

    while ( ( line = br.readLine() ) != null )
    {
        source += line;
    }

    return source;
}

私はそれをどのように呼びますか:

public static void main( String[] args )
        throws IOException
{
    WebPageUtil wpu = new WebPageUtil( "www.something.com" );

    System.out.println( wpu.getPageSource();
}

WPU コンストラクター:

public WebPageUtil( String url )
{
    this.url = url;
}

出力は常に次のようになります。

null<html><head>... //and then the rest of the source code, which is scraped correctly

何も難しいことはありませんよね?しかし、そのいまいましい「ヌル」はどこから来ているのですか?!

アドバイスをありがとう!

4

1 に答える 1