0

我制作了一个从指定网站获取 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 回答