Java URI 类 : constructor determines whether or not query is encoded?

标签 java uri

这种行为是故意的吗?

//create the same URI using two different constructors

URI foo = null, bar = null;
try { 
    //constructor: URI(uri string)
    foo = new URI("http://localhost/index.php?token=4%2F4EzdsSBg_4vX6D5pzvdsMLDoyItB");
} catch (URISyntaxException e) {} 
try { 
    //constructor: URI(scheme, authority, path, query, fragment) 
    bar = new URI("http", "localhost", "/index.php", "token=4%2F4EzdsSBg_4vX6D5pzvdsMLDoyItB", null);
} catch (URISyntaxException e) {}

//the output:
//foo.getQuery() = token=4/4EzdsSBg_4vX6D5pzvdsMLDoyItB
//bar.getQuery() = token=4%2F4EzdsSBg_4vX6D5pzvdsMLDoyItB

URI(string uri) 构造函数似乎正在解码 URI 的查询部分。我认为查询部分应该被编码?为什么另一个构造函数不解码查询部分?

最佳答案

来自 URI JavaDoc :

The single-argument constructor requires any illegal characters in its argument to be quoted and preserves any escaped octets and other characters that are present.

The multi-argument constructors quote illegal characters as required by the components in which they appear. The percent character ('%') is always quoted by these constructors. Any other characters are preserved.

因此 URI(String) 希望您正确编码所有内容,并假设 %2F 是这样一个编码的八位字节,它将被解码为 /

其他构造函数会对 % 字符进行结束编码(对于输入 %2F 产生 %252F),因此在解码后您仍然会得到 %2F

我假设构造函数之间存在偏差的目的是允许诸如 new URI(otherUri.toString())toString() 返回完全编码的 URI 之类的内容。

关于Java URI 类 : constructor determines whether or not query is encoded?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5828722/

相关文章:

Java:获取头寸价格 Google Finance API

java - 注册新的undertow SessionManager

java - 使用私钥身份验证确保 FTP 安全

image - React Native Image 元素因 URI 位置而崩溃

android - 从搜索图像的内容 URI 获取绝对文件路径

java - 为什么将 FileOutputStream 打开到二进制文件会损坏它?

java - Youtube API setScheduledStartTime

java - 将 CSV 文件导入 MySQL 表

c# - 从 URL 获取主机域?

java - 从 Google Drive 下载文件及其 URI,无需 Android 中的 Google Drive API