I made a WebConnection Java script that gets the HTML from a specified website. It works, but when I try to make things easier by automatically concatinating http://
onto the front, it does not work, despite the fact that the Strings should be the same (it gives a java.lang.IllegalArgumentException
). Here is my code:
package WebConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JOptionPane;
public class WebConnect {
URL netPage;
public WebConnect() {
String s = "http://";
s.concat(JOptionPane.showInputDialog(null, "Enter a URL:"));
System.out.println(s);
System.out.println(getNetContent(s));
//The above does not work, but the below does
//System.out.println(getNetContent(JOptionPane.showInputDialog(null, "Enter a URL:")));
}
private String getNetContent(String u) {
try {
netPage = new URL(u);
} catch(MalformedURLException ex) {
JOptionPane.showMessageDialog(null, "BAD URL!");
return "BAD URL";
}
StringBuilder content = new StringBuilder();
try{
HttpURLConnection connection = (HttpURLConnection) netPage.openConnection();
connection.connect();
InputStreamReader input = new InputStreamReader(connection.getInputStream());
BufferedReader buffer = new BufferedReader(input);
String line;
while ((line = buffer.readLine()) != null) {
content.append(line + "\n");
}
} catch(IOException e){
JOptionPane.showMessageDialog(null, "Something went wrong!");
return "There was a problem.";
}
return content.toString();
}
public static void main(String[] args) {
new WebConnect();
}
For example, if I run first section of webConnect() and type google.com
it does not work, but if I run the commented out line instead, and type http://google.com
, it does not give an error. Why?
Thanks in advance!