mbridges
mbridges

Reputation: 184

why I'm getting a "cannot find symbol" error

I'm trying to make a class that gets the source code from a URL. I dont understand why I get a "cannot find symbol error" on this line:

catch (MalformaedURLException e)

If someone could explain whats wrong that would be wonderful...Thanks

Here is my whole code:

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

}

Upvotes: 0

Views: 12252

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388416

There are multiple problems with this code.

  1. You are missing the import for java.net.MalformedURLException
  2. getSource() is not returning anything, you need to return a string from the method.
  3. You are setting spoof.setRequestProperty after starting to read from the source
  4. Your constructor is ignoring the exception instead of throwing it out
  5. There is no getter for source
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());
    }
}

Upvotes: 4

Related Questions