近来试着FTP搜索,遇到编码问题,研究了下。
Java内部的String为Unicode编码,每个字符占两个字节。
Java编解码方法如下:
- String str = "hi好啊me";
- byte[] gbkBytes=str.getBytes("GBK");
- String string=new String(gbkBytes,"GBK");
|
1、表单数据的编码
现在的问题是,在网络中,不知道客户端发过来的字节流的编码方案(发送前浏览器会对数据编码!!!各个浏览器还不一样!!!)
解决方案如下:
当然URLEncoder.encode(str, "utf-8")和URLDecoder.decode(strReceive,"utf-8")方法中的编码方案要一致。
2、网址的编码
但以上方法只适合表单数据的提交;对于URL则不行!!!原因是URLEncoder把'/'也编码了,浏览器发送时报错!!!那么,只要http://IP/子目录把http://IP/这部分原封不动(当然这部分不要有中文),之后的数据以'/'分割后分段编码即可。
代码如下:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static String encodeURL(String str, String encoding) {
- final char splitter = '/';
- try {
- StringBuilder sb = new StringBuilder(2 * str.length());
- int start = 0;
- for (int i = 0; i < str.length(); i++) {
- if (str.charAt(i) == splitter) {
- sb.append(URLEncoder.encode(str.substring(start, i),
- encoding));
- sb.append(splitter);
- start = i + 1;
- }
- }
- if (start < str.length())
- sb.append(URLEncoder.encode(str.substring(start), encoding));
- return sb.toString();
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return null;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static String encodeURLAfterHost(String str, String encoding) {
- final char splitter = '/';
- int index = str.indexOf(splitter);
- index++;
- if (index < str.length() && str.charAt(index) == splitter) {
- index++;
- index = str.indexOf(splitter, index);
- if (index > 0) {
- return str.substring(0, index + 1)
- + encodeURL(str.substring(index + 1), encoding);
- } else
- return str;
- }
- return encodeURL(str, encoding);
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static String decodeURLAfterHost(String str, String encoding) {
- final char splitter = '/';
- int index = str.indexOf(splitter);
- index++;
- if (index < str.length() && str.charAt(index) == splitter) {
- index++;
- index = str.indexOf(splitter, index);
- if (index > 0) {
- return str.substring(0, index + 1)
- + decodeURL(str.substring(index + 1), encoding);
- } else
- return str;
- }
- return decodeURL(str, encoding);
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static String decodeURL(String str, String encoding) {
- final char splitter = '/';
- try {
- StringBuilder sb = new StringBuilder(str.length());
- int start = 0;
- for (int i = 0; i < str.length(); i++) {
- if (str.charAt(i) == splitter) {
- sb.append(URLDecoder.decode(str.substring(start, i),
- encoding));
- sb.append(splitter);
- start = i + 1;
- }
- }
- if (start < str.length())
- sb.append(URLDecoder.decode(str.substring(start), encoding));
- return sb.toString();
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return null;
- }
|