지식창고

VC URLEncode 함수

2012. 1. 16. 19:21
잘 사용하던 URLEncode 함수가 특정 글자에 이상하게 동작했다.

CString EnCodeStr(CString ToCode)
{
    CString RetStr,AddStr;
    int i,max;
    unsigned short asc;
    unsigned char c;
    max = (unsigned int)ToCode.GetLength();
    for(i=0;i<max;i++)
    {
        c = ToCode[i];
        asc = c;//(unsigned int)c;
        if(asc>47 && asc<58)
        {
            RetStr+=c;//Interim[(int)i];
        }
        else if(asc>64 && asc<91)
        {
            RetStr+=c;//Interim[(int)i];
        }
        else if(asc>96 && asc<123)
        {
            RetStr+=c;//Interim[(int)i];
        }
        else if(asc==32)
        {
            RetStr+="+";
        }
        else
        {
            AddStr.Format("%%%2x",asc);
            int iv = (int)AddStr.GetAt(1);
            if((int)AddStr.GetAt(1)==32)
            {
                AddStr.SetAt(1,'0');
            }
            RetStr+=AddStr;
        }
    }
    return RetStr;
}

ks5601 에선 문제가 없는데 '똠' 이라던가 '쫒' 이란글자는 제대로 안되었다.

이것과 쌍으로 사용하는 ASP페이지의 코드를 참조해서 한글인경우 예외처리를 추가했다.

CString EnCodeStrEx( CString szToCode )
{
    CString RetStr,AddStr;
    int i,max;
    unsigned short asc;
    unsigned char c;
    max = (unsigned int)szToCode.GetLength();
    for(i=0;i<max;i++)
    {
        c = szToCode[i];
        asc = c;//(unsigned int)c;
        if(asc>47 && asc<58)
        {
            RetStr+=c;//Interim[(int)i];
        }
        else if(asc>64 && asc<91)
        {
            RetStr+=c;//Interim[(int)i];
        }
        else if(asc>96 && asc<123)
        {
            RetStr+=c;//Interim[(int)i];
        }
        else if(asc==32)
        {
            RetStr+="+";
        }
        else
        {
            //똠, 쫒 같은 글자들때문에 한글예외처리함
            if(IsDBCSLeadByte(c)){
                unsigned short asc2;
                c = szToCode[i+1];
                asc2 = c;
                AddStr.Format("%%%2x%%%2x",asc,asc2);
                i++;
            }
            else
            {
                AddStr.Format("%%%2x",asc);
                int iv = (int)AddStr.GetAt(1);
                if((int)AddStr.GetAt(1)==32)
                {
                    AddStr.SetAt(1,'0');
                }
            }
            RetStr+=AddStr;
        }
    }
    return RetStr;
}