我收到此错误消息:
java.net.URISyntaxException: Illegal character in query at index 31: http://finance.yahoo.com/q/h?s=^IXIC
My_Url = http://finance.yahoo.com/q/h?s=^IXIC
当我将其复制到浏览器地址字段时,它显示了正确的页面,它是有效的URL
,但我无法用这个来解析它:new URI(My_Url)
我试过 :My_Url=My_Url.replace("^","\\^")
, but
- 这不会是我需要的网址
- 也不起作用
这要怎么处理呢?
Frank
您需要对 URI 进行编码,以将非法字符替换为合法的编码字符。如果您首先创建一个 URL(这样您就不必自己进行解析),然后使用五参数构造函数,那么构造函数将为您进行编码。
import java.net.*;
public class Test {
public static void main(String[] args) {
String myURL = "http://finance.yahoo.com/q/h?s=^IXIC";
try {
URL url = new URL(myURL);
String nullFragment = null;
URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), nullFragment);
System.out.println("URI " + uri.toString() + " is OK");
} catch (MalformedURLException e) {
System.out.println("URL " + myURL + " is a malformed URL");
} catch (URISyntaxException e) {
System.out.println("URI " + myURL + " is a malformed URL");
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)