gpt4 book ai didi

java - 如何处理 URISyntaxException

转载 作者:IT老高 更新时间:2023-10-28 20:44:46 25 4
gpt4 key购买 nike

我收到此错误消息:

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("^","\\^"),但是

  1. 这不是我需要的网址
  2. 也不行

如何处理?

弗兰克

最佳答案

您需要对 URI 进行编码,以将非法字符替换为合法编码字符。如果您首先创建一个 URL(因此您不必自己进行解析),然后使用 five-argument constructor 创建一个 URI ,然后构造函数将为您进行编码。

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");
}
}
}

关于java - 如何处理 URISyntaxException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/749709/

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