如何编码 URI 参数值? [英] How do I encode URI parameter values?

查看:42
本文介绍了如何编码 URI 参数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想发送一个 URI 作为查询/矩阵参数的值.在将其附加到现有 URI 之前,我需要根据 RFC 2396 对其进行编码.例如,给定输入:

I want to send a URI as the value of a query/matrix parameter. Before I can append it to an existing URI, I need to encode it according to RFC 2396. For example, given the input:

http://google.com/resource?key=value1 &值2

我期望输出:

http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue1%2520%26%2520value2

java.net.URLEncoderjava.net.URI 都不会产生正确的输出.URLEncoder 用于 HTML 表单编码,与 RFC 2396 不同.URI 没有一次编码单个值的机制,因此无法知道value1 和 value2 是同一个键的一部分.

Neither java.net.URLEncoder nor java.net.URI will generate the right output. URLEncoder is meant for HTML form encoding which is not the same as RFC 2396. URI has no mechanism for encoding a single value at a time so it has no way of knowing that value1 and value2 are part of the same key.

推荐答案

Jersey's UriBuilder 根据需要使用 application/x-www-form-urlencoded 和 RFC 3986 对 URI 组件进行编码.根据 Javadoc

Jersey's UriBuilder encodes URI components using application/x-www-form-urlencoded and RFC 3986 as needed. According to the Javadoc

Builder 方法按照 application/x-www-form-urlencoded 媒体类型的规则对查询参数和 RFC 3986 的所有其他组件执行相应 URI 组件中不允许的字符的上下文编码.请注意,只有在特定组件中不允许的字符才需要进行编码,例如,提供给其中一种路径方法的路径可能包含矩阵参数或多个路径段,因为分隔符是合法字符并且不会被编码.在允许的情况下也会识别百分比编码值,并且不会进行双重编码.

Builder methods perform contextual encoding of characters not permitted in the corresponding URI component following the rules of the application/x-www-form-urlencoded media type for query parameters and RFC 3986 for all other components. Note that only characters not permitted in a particular component are subject to encoding so, e.g., a path supplied to one of the path methods may contain matrix parameters or multiple path segments since the separators are legal characters and will not be encoded. Percent encoded values are also recognized where allowed and will not be double encoded.

这篇关于如何编码 URI 参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆