admin 管理员组文章数量: 1086019
2024年4月23日发(作者:thread命令用法)
urldecoder decode()代码
URLDecoder是Java语言里的一个类,它的主要作用是将一个经
过URL编码的字符串进行解码还原成一个普通字符串。这使得在网页
浏览器中使用GET方式传递参数时,通过解码后可以获取到正常的参
数值,这样就不会出现传递中文参数乱码的问题。
URLDecoder类里的decode()方法是解码URL的核心方法,现在
我们就来分步骤阐述该方法的具体实现过程。
1. 首先解码第一个参数
```
public static String decode(String s, String enc) {
boolean needToChange = false;
int numChars = ();
StringBuffer sb = new StringBuffer(numChars > 500 ?
numChars / 2 : numChars);
int i = 0;
if (() == 0) {
throw new UnsupportedEncodingException ("URLDecoder:
empty string enc parameter");
}
char c;
byte[] bytes = null;
while (i < numChars) {
c = (i);
switch (c) {
case '+':
(' ');
i++;
needToChange = true;
break;
case '%':
/*
* Starting with this instance of %, process all
* consecutive substrings of the form %xy. Each
* substring %xy will yield a byte. Convert all
* consecutive bytes obtained this way to
whatever
* character(s) they represent in the provided
* encoding.
*/
try {
if (bytes == null)
bytes = new byte[(numChars-i)/3];
int pos = 0;
while ( ((i+2) < numChars) &&
(c=='%')) {
int v =
nt(ing(i+1,i+3),16);
if (v < 0)
throw new
IllegalArgumentException("URLDecoder: Illegal hex characters
in escape (%) pattern - negative value");
bytes[pos++] = (byte) v;
i+= 3;
if (i < numChars)
c = (i);
}
/*
* A trailing, incomplete byte encoding such
as
* "%x" will cause an exception to be thrown
*/
if ((i < numChars) && (c=='%'))
throw new IllegalArgumentException(
"URLDecoder: Incomplete trailing escape
(%) pattern");
(new String(bytes, 0, pos, enc));
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
"URLDecoder: Illegal hex characters in escape
(%) pattern - " + sage());
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
needToChange = true;
break;
default:
(c);
i++;
break;
}
}
return (needToChange? ng() : s);
}
```
2. 参数传入方法中
我们看到,该方法有两个参数,第一个参数是需要解码的字符串s,第
二个参数是编码方式enc,通常我们使用UTF-8编码方式。因此,第一
步是将需要解码的字符串s和编码方式enc传递给decode()方法。
3. 判断传递进来的编码方式enc是否为空
接下来,通过``if (() == 0)``判断编码方式是否为空,
如果编码方式enc为空,则抛出异常,提示传递进来的编码方式为空,
且不支持传递空编码方式。
4. 解码该字符串
在decode()方法中,主要是使用三种方式来判断解码的字符串是否为
需要解码的字符串:
- 转化" ":如果需要解码的字符串中有" ",则解码之后就变成" "。
- 转化"%xy":当发现"%xy"的情况时,将该字符串解析为十进制数字
v,再将数字v按照指定的编码方式enc转化为字符。
- 不进行转化:当最后一个字符不是" "或 "%xy"时,将其原样取出进
行解码。
5. 返回解码后的字符串
在解码完毕后,返回解码后的字符串。
版权声明:本文标题:urldecoder decode()代码 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1713859259a654841.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论