2013-03-05 145 views
-1

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

}

+0

您需要导入'java.net.MalformedURLException' – Apurv 2013-03-05 05:57:43

+0

拼写为MalformedURLException的是错误的.... – Pragnani 2013-03-05 06:05:59

回答

3

有多个问题与此代码。

  1. 你缺少进口的java.net.MalformedURLException
  2. getSource()不返回任何东西,你需要从方法返回一个字符串。
  3. 你开始从源头上阅读
  4. 你的构造函数被忽略扔出来
  5. 的异常,而不是有没有消气源

    进口java.io.BufferedReader中后设置spoof.setRequestProperty; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection;

    public class SourceCode {0} {0}私人字符串来源;

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

    }

+0

完美,谢谢! – mbridges 2013-03-05 06:22:17

+0

谢谢帮助了我很多! – 2016-02-23 22:32:56

相关问题