(原创)URL编码实现

代码直接上了,切记,代码中的42行跟43行的&F运算一定要加,不然的话,汉字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
/**
* @param s 需要编码的url字符串
* @param len 需要编码的url的长度
* @param new_length 编码后的url的长度
* @return char * 返回编码后的url
* @note 存储编码后的url存储在一个新审请的内存中,
* 用完后,调用者应该释放它
*/
static char * urlencode(char *s, int len, int *new_length)
{
printf( s);
printf("\n");

char *from, *start, *end, *to;
from = s;
end = s + len;
start = to = (char *) malloc(3 * len + 1);

char hexchars[] = "0123456789ABCDEF";
char c;

while (from < end) {
c = *from++;

if (c == ' ') {
*to++ = '+';
}
else if ( ('0' <= c && c <= '9')
|| ('a' <= c && c <= 'z')
|| ('A' <= c && c <= 'Z')
|| c == '/'
|| c == '.'
|| c == '-'
|| c == '_'
|| c == '='
|| c == '&')
{
*to++ = c;
}
else {
to[0] = '%';
to[1] = hexchars[(c >> 4)&0xF];
to[2] = hexchars[(c & 15)&0xF];
to += 3;
}
}
*to = 0;
if (new_length) {
*new_length = to - start;
}
return (char *) start;

}

static char* urlencode_v20(const char *s,char *pDes)
{
char pTemp[1024*5];
char pTemp2[1024];
memset(pTemp,0,sizeof(pTemp));
memset(pTemp2,0,sizeof(pTemp2));
strcpy(pTemp,s);
int nNewLen = 0;
char *pUrlEncode = urlencode(pTemp, strlen(pTemp), &nNewLen);
memset(pTemp,0,sizeof(pTemp));
strcpy(pTemp,pUrlEncode);
free(pUrlEncode);
pUrlEncode = NULL;
strcpy(pDes,pTemp);
return pDes;
}

多谢打赏
-------------本文结束感谢您的阅读-------------
0%