为什么我得到一个“找不到符号”的错误

时间:2013-03-05 05:55:46

标签: java

我正在尝试创建一个从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;
}

}

1 个答案:

答案 0 :(得分:3)

此代码存在多个问题。

  1. 您缺少java.net.MalformedURLException
  2. 的导入
  3. getSource()没有返回任何内容,您需要从方法中返回一个字符串。
  4. 您在开始阅读来源
  5. 后设置spoof.setRequestProperty
  6. 您的构造函数忽略了异常而不是将其抛出
  7. 源没有吸气剂

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

    public class SourceCode {     私有字符串源;

    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());
    }
    

    }