我一直在研究URLdecode函数,所以我可以解析在HTTP服务器上收到的POST请求,但是我遇到了打嗝。每当我向数组添加整数时,它都不会添加整数的ASCII对应项。有什么我想念的吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void copyAndTerminateString(char *dest, char *src, int len) {
if (len > 0) strncpy(dest, src, len);
dest[len] = '\0';
}
char *urldecode(char *encodedString) {
int i, n = 0, val, encodedStringLen = strlen(encodedString), stringLen = 0;
for (i = 0; i < encodedStringLen; i++) {
if (encodedString[i] == '%') {
stringLen -= 1;
} else {
stringLen++;
}
}
char *returnString = malloc(stringLen + 1), *hexValue = malloc(3);
i = 0;
printf("length = %d\r\n", stringLen);
printf("+ is %d\r\n", (int)'+');
while (encodedString[i] != '\0') {
if (encodedString[i] == '%') {
copyAndTerminateString(hexValue, encodedString + i + 1, 2);
val = strtol(hexValue, NULL, 16);
if (val != 0) {
returnString[n] = val;
}
printf("ascii \"%s\" = \"%d\"\r\n", hexValue, val);
i += 2;
} if (encodedString[i] == '+') {
returnString[n] = ' ';
} else {
returnString[n] = encodedString[i];
}
i++;
n++;
}
returnString[stringLen] = '\0';
return returnString;
}
int main(int argc, char **argv) {
char *a = "a+%2B+b+%3D%3D+13%25%21";
char *b = urldecode(a);
printf("String is: %s\r\n", b);
free(b);
return 0;
}
输出:
length = 13
+ is 43
ascii "2B" = "43"
ascii "3D" = "61"
ascii "3D" = "61"
ascii "25" = "37"
ascii "21" = "33"
String is: a B b DD 1351
预期产出:
...
String is: a + b == 13%!
答案 0 :(得分:5)
你错过了else
行:
} if (encodedString[i] == '+') {
表示在解码十六进制值后,用最后一个十六进制数字覆盖它......