我制作了一个WebConnection Java脚本,该脚本从指定的网站获取HTML。它可以工作,但是当我尝试通过在前面自动添加http://
来使事情变得更容易时,尽管字符串应该相同(给出了java.lang.IllegalArgumentException
),但它不起作用。这是我的代码:
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();
}
例如,如果我运行webConnect()的第一部分并键入
google.com
,则它不起作用,但是,如果我改为运行注释掉的行,并键入http://google.com
,则不会给出错误。为什么?提前致谢!
最佳答案
字符串是不可变的。这意味着您无法编辑内容。
更改...
String s = "http://";
s.concat(JOptionPane.showInputDialog(null, "Enter a URL:"));
至...
String s = "http://";
s = s.concat(JOptionPane.showInputDialog(null, "Enter a URL:"));