java中url汉字编码互相转换实例
java代码如下:
package com.gjob.common;
public class urltoutf8 {
//转换为%e4%bd%a0形式
public static string toutf8string(string s) {
stringbuffer sb = new stringbuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charat(i);
if (c >= 0 && c <= 255) {
sb.append(c);
} else {
byte[] b;
try {
b = string.valueof(c).getbytes("utf-8");
} catch (exception ex) {
system.out.println(ex);
b = new byte[0];
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0)
k += 256;
sb.append("%" + integer.tohexstring(k).touppercase());
}
}
}
return sb.tostring();
}
//将%e4%bd%a0转换为汉字
public static string unescape(string s) {
stringbuffer sbuf = new stringbuffer();
int l = s.length();
int ch = -1;
int b, sumb = 0;
for (int i = 0, more = -1; i < l; i++) {
/* get next byte b from url segment s */
switch (ch = s.charat(i)) {
case '%':
ch = s.charat(++i);
int hb = (character.isdigit((char) ch) ? ch - '0'
: 10 + character.tolowercase((char) ch) - 'a') & 0xf;
ch = s.charat(++i);
int lb = (character.isdigit((char) ch) ? ch - '0'
: 10 + character.tolowercase((char) ch) - 'a') & 0xf;
b = (hb << 4) | lb;
break;
case '+':
b = ' ';
break;
default:
b = ch;
}
/* decode byte b as utf-8, sumb collects incomplete chars */
if ((b & 0xc0) == 0x80) { // 10xxxxxx (continuation byte)
sumb = (sumb << 6) | (b & 0x3f); // add 6 bits to sumb
if (--more == 0)
sbuf.append((char) sumb); // add char to sbuf
} else if ((b & 0x80) == 0x00) { // 0xxxxxxx (yields 7 bits)
sbuf.append((char) b); // store in sbuf
} else if ((b & 0xe0) == 0xc0) { // 110xxxxx (yields 5 bits)
sumb = b & 0x1f;
more = 1; // expect 1 more byte
} else if ((b & 0xf0) == 0xe0) { // 1110xxxx (yields 4 bits)
sumb = b & 0x0f;
more = 2; // expect 2 more bytes
} else if ((b & 0xf8) == 0xf0) { // 11110xxx (yields 3 bits)
sumb = b & 0x07;
more = 3; // expect 3 more bytes
} else if ((b & 0xfc) == 0xf8) { // 111110xx (yields 2 bits)
sumb = b & 0x03;
more = 4; // expect 4 more bytes
} else /*if ((b & 0xfe) == 0xfc)*/{ // 1111110x (yields 1 bit)
sumb = b & 0x01;
more = 5; // expect 5 more bytes
}
/* we don't test if the utf-8 encoding is well-formed */
}
return sbuf.tostring();
}
public static void main(string[] args){
system.out.println(urltoutf8.toutf8string("你"));
system.out.println(urltoutf8.unescape("%e4%bd%a0%20%e5%a5%bd"));
}
}
############
运行结果:
%e4%bd%a0
你 好
推荐阅读