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

查看:132
本文介绍了如何编码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 & value2

我希望输出:

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

java.net.URLEncoderjava.net.URI都不会生成正确的输出. URLEncoder用于与RFC 2396不同的HTML格式编码.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的 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天全站免登陆