cURL / Mailing Lists / curl-library / Single Mail

curl-library

Re: Special characters encoding in a post HTTP request

From: Evan Martin <eeyem_at_u.washington.edu>
Date: Mon, 16 Jul 2001 01:37:13 -0700

On Mon, Jul 16, 2001 at 10:04:20AM +0200, Bescon, Guenole wrote:
> Is it a convenient method in curl for convert for converting a String into a
> MIME format called "x-www-form-urlencoded" format ?
> This method must do the following :
> * The ASCII characters 'a' through 'z', 'A' through 'Z', and '0'
> through '9' remain the same.
> * The space character ' ' is converted into a plus sign '+'.
> * All other characters are converted into the 3-character string
> "%xy", where xy is the two-digit hexadecimal representation of the lower
> 8-bits of the character.

This code is modified from code from one of my projects. Apologies in
advance if it doesn't compile, but you should be able to deduce the
intention by reading it:

/* given a string, return a malloc's urlencoded string. */
char* encode(unsigned char *string) {
        int escapecount;
        unsigned char *src, *dest;
        unsigned char *newstr;
        
        char hextable[] = { '0', '1', '2', '3', '4', '5', '6', '7',
                            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        
        if (string == NULL) return NULL;

        escapecount = 0;
        for (src = string; *src != 0; src++)
                if (!isalnum(*src)) escapecount++;
        
        /* new string length =
         * string length - chars that are encoded + 3bytes per encoded char +
         * one terminating NUL */
        newstr = (char*)malloc(strlen(string) - escapecount + (escapecount * 3) + 1);
        
        src = string;
        dest = newstr;
        while (*src != 0) {
                if (!isalnum(*src)) {
                        *dest++ = '%';
                        *dest++ = hextable[*src / 16];
                        *dest++ = hextable[*src % 16];
                        src++;
                } else {
                        *dest++ = *src++;
                }
        }
        *dest = 0;
        return newstr;
}

-- 
Evan Martin - martine_at_speakeasy.org
 http://www.speakeasy.org/~martine
_______________________________________________
Curl-library mailing list
http://curl.haxx.se/libcurl/
Received on 2001-07-16