項目中經常用到前臺傳中文參數的問題,傳中文很容易亂碼,如果是form表單post提交,就不用考慮這些問題,但是有些情況不適宜使用form表單,一般都是js中將中文進行編碼,但是在後臺如何解碼,這就存在一些差異性了。前臺肯定需要將中文encodeURIComponent,但後臺如何解碼呢?
分析情況,有如下幾種轉碼:
1、
public staticString getRealString(String input) throws UnsupportedEncodingException{
input = new String(input.getBytes("iso8859-1"),input);
return input;
}
2、
public staticString getRealString1(String input) throwsUnsupportedEncodingException{
input = java.net.URLDecoder.decode(input, "UTF-8");
return input;
}
以上兩種解碼方式,根據線上環境不同,從而可能能正常解碼,可能解析完仍然亂碼,這就跟線上服務器環境有關係啦,如果服務器進行一次轉碼,以上方式再進行轉碼,肯定仍然是亂的,還有記得在大於號項目中,如果是異步跨域的請求,後臺必須用第二種方式解碼。總之要依賴服務器環境,有沒有特定的解碼方案呢,答案是,有的。
3、
public staticString decodeURIComponent(String encodedURI) {
char actualChar;
StringBuffer buffer = new StringBuffer();
int bytePattern, sumb = 0;
for (int i =0, more = -1; i < encodedURI.length(); i++) {
actualChar = encodedURI.charAt(i);
switch (actualChar) {
case'%': {
actualChar = encodedURI.charAt(++i);
int hb = (Character.isDigit(actualChar)? actualChar -'0'
: 10 + Character.toLowerCase(actualChar) - 'a')& 0xF;
actualChar = encodedURI.charAt(++i);
int lb = (Character.isDigit(actualChar)? actualChar -'0'
: 10 + Character.toLowerCase(actualChar) - 'a')& 0xF;
bytePattern = (hb << 4) | lb;
break;
}
case'+': {
bytePattern = ' ';
break;
}
default: {
bytePattern = actualChar;
}
}
if ((bytePattern & 0xc0) == 0x80) {//10xxxxxx
sumb = (sumb << 6) | (bytePattern & 0x3f);
if (--more == 0)
buffer.append((char) sumb);
} else if((bytePattern & 0x80) == 0x00) { // 0xxxxxxx
buffer.append((char) bytePattern);
} else if((bytePattern & 0xe0) == 0xc0) { // 110xxxxx
sumb = bytePattern & 0x1f;
more = 1;
} else if((bytePattern & 0xf0) == 0xe0) { // 1110xxxx
sumb = bytePattern & 0x0f;
more = 2;
} else if((bytePattern & 0xf8) == 0xf0) { // 11110xxx
sumb = bytePattern & 0x07;
more = 3;
} else if((bytePattern & 0xfc) == 0xf8) { // 111110xx
sumb = bytePattern & 0x03;
more = 4;
} else {// 1111110x
sumb = bytePattern & 0x01;
more = 5;
}
}
return buffer.toString();
}
此種解碼方式,不依賴於服務器環境,至少在編年史項目中,我最後採用這種方式解碼,完全沒有問題,大家也可以在項目中試試。