You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swing中JTextField读取URL传入JSoup遇MalformedURLException问题求助

解决java.net.MalformedURLException: no protocol异常

问题根源

JSoup的connect()方法要求传入带完整协议前缀(如http://或https://)的URL,你当前传入的是search这类无协议的字符串,导致URL解析失败抛出异常。

解决方案

1. 自动补全协议前缀

在将输入传入JSoup前,检查并补全协议,确保URL格式合法。修改EntrySoup类的extractWebpage方法:

public static void extractWebpage(String inputLine) {
    Document document = null;
    // 去除输入两端空白字符
    String url = inputLine.trim();
    // 无协议前缀则默认添加https://
    if (!url.startsWith("http://") && !url.startsWith("https://")) {
        url = "https://" + url;
    }
    try {
        document = Jsoup.connect(url).get();
        // 此处添加网页内容提取的后续逻辑
    } catch (IOException ex) {
        ex.printStackTrace();
        // 可选:弹窗提示用户URL无效
        // JOptionPane.showMessageDialog(null, "输入的网址格式有误,请检查后重试");
    }
}

2. 提前校验输入合法性

在Swing按钮点击事件中先做基础校验,避免无效请求:

private class FileButtonHandler implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        String inputLine = input.getText().trim();
        // 检查输入是否为空
        if (inputLine.isEmpty()) {
            JOptionPane.showMessageDialog(null, "请输入有效的网址");
            return;
        }
        // 补全协议前缀
        if (!inputLine.startsWith("http://") && !inputLine.startsWith("https://")) {
            inputLine = "https://" + inputLine;
        }
        EntrySoup.extractWebpage(inputLine);
    }
}

3. 额外优化提示

如果用户输入的是搜索引擎关键词(比如"search")而非网址,需在界面明确提示输入完整网址,或添加关键词转搜索链接的逻辑(例如拼接成https://www.google.com/search?q=search)。

内容的提问来源于stack exchange,提问作者user22322280

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 14:15:15