使用有效查询解码 URL - Java

问题描述 投票:0回答:2

我有以下用 Java 解码 URL 的代码片段:

public URL decodeURL(String url) {
    try {
        return new URL(URLDecoder.decode(url, StandardCharsets.UTF_8));
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}

所以对于以下 URL

"path/to/testurl/encoding?param=1&encodedQueryParam=table%3Dtask%5EORtableISEMPTY"
我应该得到
"path/to/testurl/encoding?param=1&encodedQueryParam=table=task^ORtableISEMPTY"
但我得到
"/path/to/testurl/encoding"
.

怎样才能得到正确的结果?

java string url java-8 java-11
2个回答
0
投票

URL.getPath()
方法不包括查询参数作为结果。您将需要单独访问它。

例子:

StringBuilder fullPath = new StringBuilder(url.getPath());
if(url.getQuery() != null) {
      fullPath.append("?").append(url.getQuery());
}

0
投票

首先,当我在本地运行您的代码时,出现异常

java.net.MalformedURLException: no protocol

然后我将

https://
添加到示例 url.

最后我得到了正确的结果,代码的差异是字符集参数 所以我想这可能是 URLDecoder 类的错误导入?

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;


public void test() throws Exception{
        System.out.println(decodeURL("https://path/to/testurl/encoding?param=1&encodedQueryParam=table%3Dtask" +
                "%5EORtableISEMPTY"));
    }

    public URL decodeURL(String url) {
        try {
            return new URL(URLDecoder.decode(url, "UTF-8"));
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException(e.getMessage());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

控制台日志如下:

https://path/to/testurl/encoding?param=1&encodedQueryParam=table=task^ORtableISEMPTY
© www.soinside.com 2019 - 2024. All rights reserved.