Reputation: 184
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
Reputation: 388416
There are multiple problems with this code.
java.net.MalformedURLException
getSource()
is not returning anything, you need to return a string from the method.spoof.setRequestProperty
after starting to read from the sourceimport 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