J2ME UrlEncode


J2ME 可用的函數,類別真的太少了,在因為某些情況下總會用到下面的函數,所以記錄一下總結得來的.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;

class Test {
public static void main(String[] args) {
System.out.println(args[0] + ": " + urlEncode(args[0]));
}

private static String urlEncode(String str) {
String URL_UNRESERVED = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~";
char[] HEX = "0123456789ABCDEF".toCharArray();

StringBuffer buf = new StringBuffer();
byte[] bytes = null;

try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeUTF(str);
bytes = bos.toByteArray();
} catch (IOException e) {
}

for (int i = 2; i < bytes.length; i++) {
byte b = bytes[i];
if (URL_UNRESERVED.indexOf(b) >= 0) {
buf.append((char) b);
} else {
buf.append('%').append(HEX[(b >> 4) & 0x0f]).append(HEX[b & 0x0f]);
}
}

return buf.toString();
}
}

參考: http://wiki.forum.nokia.com/index.php/J2ME_Google_%E5%9C%B0%E5%9C%96_API