Url解码代码
Url编码与解码的代码,使用WTL的CString,支持日文字符
CStringW ConvertUTF8ToUTF16(const CStringA& utf8)
{
int wLen = MultiByteToWideChar(CP_UTF8, 0, utf8, utf8.GetLength(), 0, 0);
CStringW buf;
WCHAR* dd = buf.GetBuffer(wLen);
wLen = MultiByteToWideChar(CP_UTF8, 0, utf8, utf8.GetLength(), dd, wLen);
buf.ReleaseBuffer(wLen);
return buf;
}
CStringW DecodeUrl(const std::string& src)
{
CStringW dstUrlW(L"");
int srclen = (int)src.size();
std::string dst;
for (int i = 0; i < srclen; i++) {
if (src[i] == '%') {
if (isxdigit(src[i + 1]) && isxdigit(src[i + 2])) {
char c1 = src[++i];
char c2 = src[++i];
c1 = c1 - 48 - ((c1 >= 'A') ? 7 : 0) - ((c1 >= 'a') ? 32 : 0);
c2 = c2 - 48 - ((c2 >= 'A') ? 7 : 0) - ((c2 >= 'a') ? 32 : 0);
dst += (unsigned char)(c1 * 16 + c2);
}
}
else if (src[i] == '+') {
dst += ' ';
}
else {
dst += src[i];
}
}
if (dst.size() > 0) {
dstUrlW = ConvertUTF8ToUTF16(CStringA(dst.c_str()));
}
return dstUrlW;
}
void EncodeUrl(char* dst, const char* src)
{
while(*src){
unsigned char c = static_cast<unsigned char>(*src);
if(c == ' ' ){
*dst++ = '+';
}
else if( isalnum( c ) || c == '$' || c == '-' || c == '_' || c == '.' ||
c == '!' || c == '*' || c == '/'' || c == '(' || c == ')' || c == ',' ){
*dst++ = c;
}
else{
*dst++ = '%';
unsigned char nibble = (c >> 4) & 0xF;
*dst++ = ( nibble < 10 ? nibble + '0' : nibble - 10 + 'A' );
nibble = c & 0xF;
*dst++ = ( nibble < 10 ? nibble + '0' : nibble - 10 + 'A' );
}
src++;
}
*dst = '/0';
}