VC URLEncode UrlDecode

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

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);
BYTE b = 0;

//alloc out buffer
pOutBuf = (LPBYTE)sOut.GetBuffer(nLen*3 - 2);//new BYTE [nLen * 3];

if(pOutBuf)
{
pInTmp = pInBuf;
pOutTmp = pOutBuf;

// do encoding
while (*pInTmp)
{
if(isalnum(*pInTmp))
*pOutTmp++ = *pInTmp;
else
if(isspace(*pInTmp))
*pOutTmp++ = '+';
else
{
*pOutTmp++ = '%';
*pOutTmp++ = toHex(*pInTmp>>4);
*pOutTmp++ = toHex(*pInTmp%16);
}
pInTmp++;
}
*pOutTmp = '\0';
//sOut=pOutBuf;
//delete [] pOutBuf;
sOut.ReleaseBuffer();
}
sIn.ReleaseBuffer();
return sOut;
}

UrlDecode:
#define IsHexNum(c) ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'))

CString Utf8ToStringT(LPSTR str)
{
_ASSERT(str);
USES_CONVERSION;
WCHAR *buf;
int length = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
buf = new WCHAR[length+1];
ZeroMemory(buf, (length+1) * sizeof(WCHAR));
MultiByteToWideChar(CP_UTF8, 0, str, -1, buf, length);

return (CString(W2T(buf)));
}

CString UrlDecode(LPCTSTR url)
{
_ASSERT(url);
USES_CONVERSION;
LPSTR _url = T2A(const_cast<LPTSTR>(url));
int i = 0;
int length = (int)strlen(_url);
CHAR *buf = new CHAR[length];
ZeroMemory(buf, length);
LPSTR p = buf;
while(i < length)
{
if(i <= length -3 && _url[i] == '%' && IsHexNum(_url[i+1]) && IsHexNum(_url[i+2]))
{
sscanf(_url + i + 1, "%x", p++);
i += 3;
}
else
{
*(p++) = _url[i++];
}
}
return Utf8ToStringT(buf);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值