【问题标题】:URISyntaxException - How to deal with urls with %URISyntaxException - 如何使用 % 处理 url
【发布时间】:2025-12-18 02:10:02
【问题描述】:

我对 Java 还很陌生,遇到了这个问题。我试过搜索,但没有得到正确的答案。

例如,我有一个字符串

String name = anything 10%-20% 04-03-07

现在我需要用这个字符串名称构建一个 url 字符串,如下所示。

http://something.com/test/anything 10%-20% 04-03-07

我尝试用 %20 替换空格,现在我得到的新网址为

http://something.com/test/anything%2010%-20%%2004-03-07

当我使用这个 url 并在 firefox 中触发它时,它可以正常工作,但是在 Java 中处理时它显然会抛出

Exception in thread "main" java.lang.IllegalArgumentException
at java.net.URI.create(Unknown Source)
at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:69)
Caused by: java.net.URISyntaxException: Malformed escape pair at index 39 : 
at java.net.URI$Parser.fail(Unknown Source)
at java.net.URI$Parser.scanEscape(Unknown Source)
at java.net.URI$Parser.scan(Unknown Source)
at java.net.URI$Parser.checkChars(Unknown Source)
at java.net.URI$Parser.parseHierarchical(Unknown Source)
at java.net.URI$Parser.parse(Unknown Source)
at java.net.URI.<init>(Unknown Source)
... 6 more

这是代码抛出错误

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);

【问题讨论】:

    标签: url http-get


    【解决方案1】:

    还使用%25 编码百分号。

    http://something.com/test/anything 10%-20% 04-03-07 可以与http://something.com/test/anything%2010%25-20%25%2004-03-07 一起使用。

    您应该可以为此使用例如 URLEncoder.encode - 请记住,您需要对路径部分进行 urlencode,而不是在此之前的任何内容,例如

    String encodedUrl =
        String.format("http://something.com/%s/%s",
          URLEncoder.encode("test", "UTF-8"),
          URLEncoder.encode("anything 10%-20% 04-03-07", "UTF-8")
        );
    

    注意:URLEncoder 将空格编码为+ 而不是%20,但它应该同样有效,两者都可以。

    【讨论】:

    • 谢谢,效果很好。我试图逃避它。没有从替代的角度思考。
    【解决方案2】:

    您可以使用 java.net.URI 从您的字符串创建一个 uri

    String url = "http://something.com/test/anything 10%-20% 04-03-07"
    
    URI uri = new URI(
        url,
        null);
    String request = uri.toASCIIString();
    
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(request);
    HttpResponse response = httpclient.execute(httpget);
    

    【讨论】: