gpt4 book ai didi

Java获取网页源码包含 "null"开头

转载 作者:行者123 更新时间:2023-12-02 06:57:26 28 4
gpt4 key购买 nike

出于某种奇怪的原因,当我尝试使用 URLConnection 获取网页源时,我在输出中得到“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

没什么难的,对吧​​?但是那个该死的“null”从哪里来?!

感谢您的建议!

最佳答案

您正在将 String 源初始化为 null 值,因此它的值将转换为第一个 String 上的文字“null” while 循环中的串联。

使用空字符串代替

String source = "";

或者更好地使用StringBuilder

关于Java获取网页源码包含 "null"开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17135632/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com