0

我正在尝试创建一个从 URL 获取源代码的类。我不明白为什么我在这一行得到“找不到符号错误”:

catch (MalformaedURLException e)

如果有人能解释什么是错的,那就太好了......谢谢

这是我的整个代码:

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

public class SourceCode
{
private String source;
public SourceCode(String url)
{
    try
    {
        URL page = new URL(url);
        this.source = getSource(page);
    }
    catch (MalformedURLException e)
    {
        e.printStackTrace();
    }
}

public String getSource(URL url) throws Exception
{

        URLConnection spoof = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(spoof.getInputStream()));
        String strLine = "";

        spoof.setRequestProperty( "User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; H010818)" );


        while ((strLine = in.readLine()) != null)
        {
            strLine = strLine + "\n";
        }
        return strLine;
}

}

4

1 回答 1

4

此代码存在多个问题。

  1. 您缺少导入java.net.MalformedURLException
  2. getSource()没有返回任何内容,您需要从该方法返回一个字符串。
  3. spoof.setRequestProperty在开始从源读取后进行设置
  4. 您的构造函数忽略异常而不是将其抛出
  5. 源没有吸气剂
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class SourceCode {
    private String source;

    public SourceCode(URL pageURL) throws IOException {
        this.source = getSource(pageURL);
    }

    public String getSource() {
        return source;
    }

    private String getSource(URL url) throws IOException {
        URLConnection spoof = url.openConnection();
        StringBuffer sb = new StringBuffer();

        spoof.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; H010818)");
        BufferedReader in = new BufferedReader(new InputStreamReader(spoof.getInputStream()));

        String strLine = "";
        while ((strLine = in.readLine()) != null) {
            sb.append(strLine);
        }

        return sb.toString();
    }

    public static void main(String[] args) throws IOException {
        SourceCode s = new SourceCode(new URL("https://www.google.co.in/"));
        System.out.println(s.getSource());
    }
}
于 2013-03-05T06:00:38.800 回答