0

指定した 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、エラーは発生しません。なんで?

前もって感謝します!

4

1 に答える 1

2

文字列は不変です。これは、コンテンツを編集できないことを意味します。

変化する...

String s = "http://";
s.concat(JOptionPane.showInputDialog(null, "Enter a URL:"));

に...

String s = "http://";
s = s.concat(JOptionPane.showInputDialog(null, "Enter a URL:"));
于 2013-03-07T16:15:07.643 に答える