URL特殊字符处理

char hexVals[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
string CURLEncode::csUnsafeString= "\"<>%\\^[]`+$,@:;/!#?=&";
string convert(char val) 
{
    string csRet;
    csRet += "%";
    csRet += decToHex(val, 16);   
    return  csRet;
}
string decToHex(char num, int radix)
{   
    int     temp=0;   
    string  csTmp;
    int num_char;
    num_char = (int) num;
     
    // ISO-8859-1 
    // IF THE IF LOOP IS COMMENTED, THE CODE WILL FAIL TO GENERATE A 
    // PROPER URL ENCODE FOR THE CHARACTERS WHOSE RANGE IN 127-255(DECIMAL)
    if (num_char < 0)
        num_char = 256 + num_char;
 
    while (num_char >= radix)
    {
        temp = num_char % radix;
        num_char = (int)floor((num_char / radix) * 1.0);
        csTmp = hexVals[temp];
    }
     
    csTmp += hexVals[num_char];
 
    if(csTmp.length() < 2)
    {
        csTmp += '0';
    }
 
    string strdecToHex = csTmp;
    // Reverse the String
    std::reverse(strdecToHex.begin(), strdecToHex.end());
         
    return strdecToHex;
}
bool isUnsafe(char compareChar)
{
    bool bcharfound = false;
    char tmpsafeChar;
    int m_strLen = 0;
     
    m_strLen = csUnsafeString.length();
    for(int ichar_pos = 0; ichar_pos < m_strLen ;ichar_pos++)
    {
        tmpsafeChar = csUnsafeString[ichar_pos]; 
        if(tmpsafeChar == compareChar)
        { 
            bcharfound = true;
            break;
        } 
    }
 
    int char_ascii_value = 0;
    //char_ascii_value = __toascii(compareChar);
    char_ascii_value = (int) compareChar;
 
    if(bcharfound == false &&  char_ascii_value > 32 && char_ascii_value < 123)
    {
        return false;
    }
    // found no unsafe chars, return false       
    else
    {
        return true;
    }
     
    return true;
}
 
string URLEncode(string strEncode)
{
    string  strSrc;
    string    strDest;   
 
    strSrc = strEncode;   
    for(int i = 0; i < strSrc.length(); i++)
    {
        char ch = strSrc[i];
        if (ch < ' ') 
        {
            ch = ch;
        }
 
        if(!isUnsafe(ch))
        {
            // Safe Character               
            strDest += ch;
        }
        else
        {
            // get Hex Value of the Character
            strDest += convert(ch);
        }
    }
     
    return strDest;
}
Licensed under CC BY-NC-SA 4.0
Built with Hugo
主题 StackJimmy 设计