Ads 468x60px

##EasyReadMore##

02 7月, 2014

url encode for htttp post

有時候 server 不接受中文網址的時候
就需要 url encode 了
int url_post_encode(char *str, int max_len)
{
    char *target;
    unsigned char *source;
    int index;
    const char DEC2HEX[] = "0123456789ABCDEF";

    // malloc
    target = (char*)malloc(strlen(str)*3);
    if (target == NULL) return -1;
    memset(target, 0, strlen(str)*3);

    // encode
    index = 0;
    source = (unsigned char *)str;
    while (*source && (index<(max_len-1))) {
        if (*source == '%') {
            target[index++] = '%';
            target[index++] = '2';
            target[index++] = '5';
        }
        else if (*source == ' ') {
            target[index++] = '+';
        }
        else if( (*source >= 0x61 && *source <= 0x7A) ||(*source >= 0x41 && *source <= 0x5A) || (*source >=0x30 && *source <= 0x39) || *source == '.' || *source == '_' || *source == '=' || *source == '&') {
            target[index++] = *source;
        }
        else {
            target[index++] = '%';
            target[index++] = DEC2HEX[*source >> 4];
            target[index++] = DEC2HEX[*source & 0x0F];
        }
        source++;
    }
    memcpy(str, target, strlen(target)+1);
    return 0;
}

Character range(decimal)
http://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c4029/URL-Encoding.htm

0 意見:

張貼留言

 
Blogger Templates