指定した Web サイトから HTML を取得する WebConnection Java スクリプトを作成しました。それは機能しますが、前面に自動的に連結して物事を簡単にしようとすると、文字列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
、エラーは発生しません。なんで?
前もって感謝します!