gpt4 book ai didi

java - 尝试运行 Google Search Api 时出现 StringIndexOutofBoundsException

转载 作者:行者123 更新时间:2023-11-30 03:37:03 25 4
gpt4 key购买 nike

我正在尝试从下面的 SO 链接运行 google search api :- How can you search Google Programmatically Java API下面是我的代码:-

public class RetrieveArticles {

public static void main(String[] args) throws UnsupportedEncodingException, IOException {
// TODO Auto-generated method stub

String google = "http://www.google.com/news?&start=1&q=";
String search = "Police Violence in USA";
String charset = "UTF-8";
String userAgent = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"; // Change this to your company's name and bot homepage!

Elements links = Jsoup.connect(google + URLEncoder.encode(search, charset)).userAgent(userAgent).get().children();

for (Element link : links) {
String title = link.text();
String url = link.absUrl("href"); // Google returns URLs in format "http://www.google.com/url?q=<url>&sa=U&ei=<someKey>".
url = URLDecoder.decode(url.substring(url.indexOf('=') +1, url.indexOf('&')), "UTF-8");

if (!url.startsWith("http")) {
continue; // Ads/news/etc.
}
System.out.println("Title: " + title);
System.out.println("URL: " + url);
}
}
}

当我尝试运行此程序时,出现以下错误。谁能帮我解决这个问题吗?

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1911)
at google.api.search.RetrieveArticles.main(RetrieveArticles.java:34)

提前致谢。

最佳答案

问题就在这里:

url.substring(url.indexOf('=') +1, url.indexOf('&'))

url.indexOf('=')url.indexOf('&') 返回 -1,这是 subString< 中的非法参数.

您应该先验证正在解析的 url,然后再假设它包含 =&

关于java - 尝试运行 Google Search Api 时出现 StringIndexOutofBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27620780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com