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

安卓App部分设备出现StringIndexOutOfBoundsException问题求助

解决StringIndexOutOfBoundsException的跨设备兼容问题

这问题我做爬虫类安卓应用时也踩过同款坑!核心原因是你没处理indexOf()找不到目标字符串时返回-1的情况——不同设备或网络环境下,服务器返回的网页内容可能存在差异(比如地区缓存、页面版本更新、甚至反爬策略的差异化返回),导致某个索引查找失败,直接调用substring()就触发了异常。

你的代码里的隐患

从你给出的代码片段来看:

int startIndex = FullPage.indexOf("//");
int endIndex = FullPage.indexOf("?", startIndex);
String DownloadableLink = FullPage.substring(startIndex, endIndex);

如果网页内容里没有//,startIndex会变成-1;或者在startIndex之后找不到?,endIndex也会是-1。这两种情况直接调用substring()都会抛出StringIndexOutOfBoundsException,而部分设备能正常运行,只是刚好拿到的网页内容符合你的索引查找条件而已。

修复方案:先做合法性校验

在提取子串前,必须先检查两个索引的合法性,确保不会出现无效索引:

try {
    Document document = Jsoup.connect(PostLink)
            .header("Accept-Encoding", "gzip, deflate")
            .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0")
            .get();
    String FullPage = document.toString();
    int startIndex = FullPage.indexOf("//");
    int endIndex = FullPage.indexOf("?", startIndex);
    
    // 关键判断:确保两个索引都有效,且结束索引在起始索引之后
    if (startIndex != -1 && endIndex != -1 && endIndex > startIndex) {
        String DownloadableLink = FullPage.substring(startIndex, endIndex);
        // 这里写后续处理DownloadableLink的逻辑
    } else {
        // 处理找不到目标链接的情况,比如给用户提示、记录日志或重试
        Log.e("LinkExtract", "无法定位可下载链接,页面内容可能已变更");
    }
} catch (IOException e) {
    // 别忘了捕获网络请求相关的异常
    e.printStackTrace();
}

更靠谱的优化建议

其实用Jsoup本身的HTML解析能力提取链接,比粗暴的字符串索引操作稳定得多。比如如果目标链接在某个特定标签里,直接用选择器定位:

// 示例:假设可下载链接在class为"download-btn"的<a>标签中
Element downloadBtn = document.select("a.download-btn").first();
if (downloadBtn != null) {
    String downloadableUrl = downloadBtn.attr("href");
    // 处理链接逻辑
}

这种方式不受页面局部内容变动的影响,能大幅降低跨设备的兼容性问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:44:22