URL编码

编码:字符 变成 %+对应的ascii码
解码:取%后的两位变成acsii码取对应的字符
   ContextType为application/x-www-form-urlencoded时 空格 编码为 +
   英文字母,数字编码可以不变
一般汉字可以转成UTF8格式在编码。
 encode:

1 unsigned char to_byte(const unsigned char x)
2 {
3 return (x>9)?x+55 :x+48;
4 }
5
6  int url_encode(constchar* src,char* dest)
7 {
8 int len = strlen(src);
9 unsigned char tb =0;
10 int i =0;
11 for (int j=0;j<len;j++)
12 {
13 tb = (unsigned char) src[j];
14 if ( (tb<'9'&& tb>'0') || (tb<'Z'&& tb>'A') || (tb<'z'&& tb>'a') )
15 {
16 dest[i++] = tb;
17 continue;
18 }
19 elseif ( tb =='')
20 {
21 dest[i++] ='+';
22 continue;
23 }
24 else
25 {
26 dest[i++] ='%';
27 dest[i++] = to_byte(tb /16);
28 dest[i++] = to_byte(tb %16);
29 }
30 }
31 return i;
32 }


 decode:

1 int to_num(unsigned char x)
2 {
3 //65-90 97-122 48-57
4  if (x<'9')
5 return x-48;
6 elseif ( x <90)
7 return x-55 ;
8 else
9 return x-87;
10 }
11
12 int url_decode(constchar* src,char* dest)
13 {
14 int len = strlen(src);
15 int i =0;
16 int now =0;
17 while (now<len)
18 {
19 if (src[now] =='+')
20 dest[i++] ='';
21 elseif ( src[now] =='%')
22 {
23 int num = to_num( src[now+++1])*16;
24 num += to_num(src[now+++1]);
25 dest[i++] = num;
26 }
27 else
28 dest[i++] = src[now];
29 now++;
30 }
31 return i;
32 }
原文地址:https://www.cnblogs.com/v2m_/p/1952655.html