Search results for 'URLDecode'. 1 post(s) found.

  1. 2009/03/24 URL Encode, Decode function for MFC
2009/03/24 08:46

URL Encode, Decode function for MFC


Here's the good example for URL Encoding & Decoding.

inline BYTE toHex(const BYTE &x)
{
    return x > 9 ? x + 55: x + 48;
}

inline BYTE toByte(const BYTE &x)
{
    return x > 57? x - 55: x - 48;
}

CString URLDecode(CString sIn)
{
    CString sOut;
    const int nLen = sIn.GetLength() + 1;
    register LPBYTE pOutTmp = NULL;
    LPBYTE pOutBuf = NULL;
    register LPBYTE pInTmp = NULL;
    LPBYTE pInBuf =(LPBYTE)sIn.GetBuffer(nLen);
    //alloc out buffer
    pOutBuf = (LPBYTE)sOut.GetBuffer(nLen);
   
    if(pOutBuf)
    {
        pInTmp   = pInBuf;
        pOutTmp = pOutBuf;
        // do encoding
        while (*pInTmp)
        {
            if('%'==*pInTmp)
            {
                pInTmp++;
                *pOutTmp++ = (toByte(*pInTmp)%16<<4) + toByte(*(pInTmp+1))%16;
                pInTmp++;
            }
            else if('+'==*pInTmp)
                *pOutTmp++ = ' ';
            else
                *pOutTmp++ = *pInTmp;
            pInTmp++;
        }
        *pOutTmp = '\0';
        sOut.ReleaseBuffer();
    }
    sIn.ReleaseBuffer();
   
    return sOut;
}

CString URLEncode(CString sIn)
{
    CString sOut;
    const int nLen = sIn.GetLength() + 1;
    register LPBYTE pOutTmp = NULL;
    LPBYTE pOutBuf = NULL;
    register LPBYTE pInTmp = NULL;
    LPBYTE pInBuf =(LPBYTE)sIn.GetBuffer(nLen);
    //alloc out buffer
    pOutBuf = (LPBYTE)sOut.GetBuffer(nLen*3);
   
    if(pOutBuf)
    {
        pInTmp   = pInBuf;
        pOutTmp = pOutBuf;
        // do encoding
        while (*pInTmp)
        {
            if(isalnum(*pInTmp) || '-'==*pInTmp || '_'==*pInTmp || '.'==*pInTmp)
                *pOutTmp++ = *pInTmp;
            else if(isspace(*pInTmp))
                *pOutTmp++ = '+';
            else
            {
                *pOutTmp++ = '%';
                *pOutTmp++ = toHex(*pInTmp>>4);
                *pOutTmp++ = toHex(*pInTmp%16);
            }
            pInTmp++;
        }
        *pOutTmp = '\0';
        sOut.ReleaseBuffer();
    }
    sIn.ReleaseBuffer();
   
    return sOut;
}

Above sample code use CString, so if you want to use it on another type of development environment such as gcc or something like that, you need to add some more stuffs because it may not support CString class.
Trackback 0 Comment 0

Trackback : Cannot send a trackbact to this post.