C++ 转义MFC字符串的URL
如何对MFC CString进行URL转义?我为可能遇到此解决方案的其他人创建了一个包装函数。还需要链接到Wininet.lib并包括Wininet.hC++ 转义MFC字符串的URL,c++,mfc,urlencode,cstring,C++,Mfc,Urlencode,Cstring,如何对MFC CString进行URL转义?我为可能遇到此解决方案的其他人创建了一个包装函数。还需要链接到Wininet.lib并包括Wininet.h bool EscapeURL ( CString& url, DWORD options = ICU_DECODE | ICU_ENCODE_PERCENT ) { DWORD bytes = url.GetLength () + 1; LPTSTR escapedString = new
bool EscapeURL ( CString& url, DWORD options = ICU_DECODE | ICU_ENCODE_PERCENT )
{
DWORD bytes = url.GetLength () + 1;
LPTSTR escapedString = new TCHAR[bytes + 1];
escapedString[0] = 0;
// First read will generate the correct byte count for the return string
//
bool result = InternetCanonicalizeUrl ( url.GetBuffer (), escapedString, &bytes, options );
if ( !result )
{
// Resize the String
//
delete [] escapedString;
escapedString = new TCHAR[bytes];
escapedString[0] = 0;
result = InternetCanonicalizeUrl ( url.GetBuffer (), escapedString, &bytes, options );
}
if ( result )
{
url = escapedString;
delete [] escapedString; // Thanks The Steve
}
else
{
// Optional
// If the call fails return the message in the url
//
DWORD errorMessageID = ::GetLastError ();
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA ( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
std::string message ( messageBuffer, size );
LocalFree ( messageBuffer );
url = message.c_str ();
}
return result;
}
用法
CString internetUse = "The Internet is %%4 <pr0n>";
EscapeURL ( internetUse );
// internetUse = 0x01538890 "The%20Internet%20is%20%25%254%20%3Cpr0n%3E"
CString internetUse=“互联网是%%4”;
EscapeURL(互联网使用);
//internetUse=0x01538890“互联网%20是%20%25%254%20%3Cpr0n%3E”
快速解决方案,很好。我本来打算发布源代码的,但这就足够了!不直接获取或返回CString,但来回转换很简单。此函数使我的umlaute混乱。您正在泄漏内存。已复制转义字符串,但从未删除。