我有以下用 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"
.
怎样才能得到正确的结果?
URL.getPath()
方法不包括查询参数作为结果。您将需要单独访问它。
例子:
StringBuilder fullPath = new StringBuilder(url.getPath());
if(url.getQuery() != null) {
fullPath.append("?").append(url.getQuery());
}
首先,当我在本地运行您的代码时,出现异常
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