如何修复 Java 中格式错误的 URL 异常?



我正在编写一个从在线网站获取信息的程序,而获取内容的函数在其他项目上不起作用。我使用了调试模式,我相信问题来自声明 URL 对象的行。文档说,格式错误的 URL 异常只有在协议错误或字符串为 null 时才会发生

try {
System.out.println("URL is "+ trainServiceURL); 
url = new URL(trainServiceURL); //gets webpage

打印行输出:

URL is http://www.realtimetrains.co.uk/search/advancedhandler?type=advanced&location=2A01&toc=All&earlier_cp=&later_cp=&timespan=now&show=all&order=wtt&stp_wtt=1&stp_var=1&stp_stp=1&stp_can=0

这适用于谷歌浏览器,并且具有正确的协议。我在 try 语句的末尾有格式错误的 URL 异常和 IO 异常的 catch 语句,但它们似乎都没有触发(它们旨在打印堆栈跟踪(。问题是什么,我该如何解决?

我找不到你的代码有问题,至少你给我们的代码没有问题。

这是我的代码:

public static void main(String[] args) {
URL url;
try {
url = new URL("http://www.realtimetrains.co.uk/search/advancedhandler?type=advanced&location=2A01&toc=All&earlier_cp=&later_cp=&timespan=now&show=all&order=wtt&stp_wtt=1&stp_var=1&stp_stp=1&stp_can=0");
} catch (Exception e) {
// handle exception
}
}

最新更新