#include <stdio.h>
#include <string.h>
int URLEncode(const char* str, const int strSize, char* result, const int resultSize)
{
int i;
int j = 0;//for result index
char ch;
if ((str==NULL) || (result==NULL) || (strSize<=0) || (resultSize<=0)) {
return 0;
}
for ( i=0; (i<strSize)&&(j<resultSize); ++i) {
ch = str[i];
if (((ch>='A') && (ch<'Z')) ||
((ch>='a') && (ch<'z')) ||
((ch>='0') && (ch<'9'))) {
result[j++] = ch;
} else if (ch == ' ') {
result[j++] = '+';
} else if (ch == '.' || ch == '-' || ch == '_' || ch == '*') {
result[j++] = ch;
} else {
if (j+3 < resultSize) {
sprintf(result+j, "%%%02X", (unsigned char)ch);
j += 3;
} else {
return 0;
}
}
}
result[j] = '\0';
return j;
}
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;
}
int main()
{
char *p = "测试";
printf("p:%s\n",p);
char result[32];
char deresult[32];
URLEncode(p,strlen(p),result,32);
printf("result:%s\n",result);
urldecode(result,strlen(result));
printf("%s\n",result);
}