re | C语言url编码解码
C语言url编码解码
参考了网上一段代码改的,,,忘了记录来源了。。。
主要要用到的功能是解码部分。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int hex2dec(char c)
{
if ('0' <= c && c <= '9')
{
return c - '0';
}
else if ('a' <= c && c <= 'f')
{
return c - 'a' + 10;
}
else if ('A' <= c && c <= 'F')
{
return c - 'A' + 10;
}
else
{
printf("> urldecode err\n");
return -1;
}
}
char dec2hex(short int c)
{
if (0 <= c && c <= 9)
{
return c + '0';
}
else if (10 <= c && c <= 15)
{
return c + 'A' - 10;
}
else
{
printf("> urldecode err\n");
return -1;
}
}
//编码一个url
void urlencode(char* url)
{
int i = 0;
int len = strlen(url);
int res_len = 0;
unsigned char* res = (unsigned char*)malloc(3*len+1); // 动态分配3倍的长度
for (i = 0; i < len; ++i)
{
char c = url[i];
if ( ('0' <= c && c <= '9') ||
('a' <= c && c <= 'z') ||
('A' <= c && c <= 'Z') ||
c == '/' || c == '.')
{
res[res_len++] = c;
}
else
{
int j = (short int)c;
if (j < 0)
j += 256;
int i1, i0;
i1 = j / 16;
i0 = j - i1 * 16;
res[res_len++] = '%';
res[res_len++] = dec2hex(i1);
res[res_len++] = dec2hex(i0);
}
}
res[res_len] = '\0';
strcpy(url, (const char*)res);
free(res);
}
// 解码url
void urldecode(char* url)
{
int i = 0;
unsigned int len = strlen(url); // 长度
int res_len = 0;
unsigned char* res = (unsigned char*)malloc(len+1); // 动态分配同样的长度
for (i = 0; i < len; ++i)
{
char c = url[i];
if (c != '%')
{
res[res_len++] = c;
}
else
{
char c1 = url[++i];
char c0 = url[++i];
int num = 0;
num = hex2dec(c1) * 16 + hex2dec(c0);
res[res_len++] = num;
}
}
res[res_len] = '\0';
strcpy(url, (const char*)res);
free(res);
}
int main(int argc, char *argv[])
{
char url[100] = "http://'测试/@mike./,././[;]";
printf("原文:%s \n", url);
urlencode(url); //编码后
printf("编码: %s\n", url);
urldecode(url); //解码后
printf("解码: %s\n", url);
return 0;
}
本文来自博客园,作者:Mz1,转载请注明原文链接:https://www.cnblogs.com/Mz1-rc/p/16348158.html
如果有问题可以在下方评论或者email:mzi_mzi@163.com