url编解码实现

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
static unsigned char char_to_hex(unsigned char x)
{
return (unsigned char)(x > 9 ? x + 55 : x + 48);
}

static int is_alpha_number_char(unsigned char c)
{
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
return 1;
return 0;
}

//url编码实现
void urlencode(unsigned char * src, int src_len, unsigned char * dest, int dest_len)
{
unsigned char ch;
int len = 0;
while(len < (dest_len - 4) && *src)
{
ch = (unsigned char) * src;
if(*src == ' ')
{
*dest++ = '+';
}
else if(is_alpha_number_char(ch) || strchr("-_.!~*'()", ch))
{
*dest++ = *src;
}
else
{
*dest++ = '%';
*dest++ = char_to_hex((unsigned char)(ch >> 4));
*dest++ = char_to_hex((unsigned char)(ch % 16));
}
++src;
++len;
}
*dest = 0;
return ;
}


/**
* @param str 需要解码的url字符串
* @param len 需要解码的url的长度
* @return int 返回解码后的url长度
*/
int urldecode(char *str, int len)
{
char *dest = str;
char *data = str;

int value;
int c;

while(len--)
{
if(*data == '+')
{
*dest = ' ';
}
else if(*data == '%' && len >= 2 && isxdigit((int) * (data + 1))
&& isxdigit((int) * (data + 2)))
{

c = ((unsigned char *)(data + 1))[0];
if(isupper(c))
c = tolower(c);
value = (c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10) * 16;
c = ((unsigned char *)(data + 1))[1];
if(isupper(c))
c = tolower(c);
value += c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10;

*dest = (char)value ;
data += 2;
len -= 2;
}
else
{
*dest = *data;
}
data++;
dest++;
}
*dest = '\0';
return dest - str;
}