c++ - How do I call the UrlCanonicalize API function correctly? -
hresult urlcanonicalize( _in_ pctstr pszurl, _out_ ptstr pszcanonicalized, _inout_ dword *pcchcanonicalized, dword dwflags ); example:
lpctstr pszurl = url.c_str(); lpstr pszoutput = new char[ strurl.length ]; dword* dwcount = new dword[ strurl.length ]; hres = urlcanonicalize( pszurl, pszoutput,dwcount, url_escape_unsafe ); output:
e_invalidarg this api fails , returns e_invalidarg every time try call it. please give me working code snippet call urlcanonicalize function.
if know c++ language, the sdk documentation function pretty tells need know:
- you pass c-style nul-terminated string contains url.
- you pass pointer buffer receive output string.
- you pass 1 or more flags customize function's behavior.
- and finally, returns
hresultvalue, error code. if succeeds, values_ok. if fails, other error code.
it works this:
std::wstring originalurl(l"http://www.example.com/hello/cruel/../world/"); // allocate buffer of appropriate length. // needs @ least long input string. std::wstring canonicalurl(originalurl.length() + 1, l'\0'); dword length = originalurl.length() + 1; // call function modify string. hresult hr = urlcanonicalize(originalurl.c_str(), // input string &canonicalurl[0], // buffer &length, // pointer dword contains length of buffer url_unescape | url_escape_unsafe); if (succeeded(hr)) { // function succeeded. // canonicalized url in canonicalurl string. messagebox(nullptr, canonicalurl.c_str(), l"the url is:", mb_ok); } else { // function failed. // hr variable contains error code. throw std::runtime_error("the urlcanonicalize function failed."); } if want make sure buffer sufficiently long (and avoid having handle error), use constant internet_max_url_length (declared in wininet.h) when allocating it:
std::wstring canonicalurl(internet_max_url_length, l'\0'); dword length = internet_max_url_length; the code tried has couple of problems:
you've incorrectly initialized
dwcountvariable. function wants pointer, doesn't mean should declare variable pointer. nor want array; singledwordvalue. need declare regulardword, , use address-of operator (&) pass function pointer variable. right now, you're passing function garbage, it's failing.you're using c-style strings, should avoid in c++ code. use c++ string class (
std::wstringwindows code), exception safe , manages memory you. know,c_str()member function gives easy access c-style nul-terminated string c apis want. works fine, not need use raw character arrays yourself. avoidnewwhenever possible.
potentially, third problem you're trying use c++ string type std::string instead of std::wstring. former 8-bit string type , doesn't support unicode in windows environment. want std::wstring, wide string unicode support. it's windows api functions expect if have unicode symbol defined project (which default).
Comments
Post a Comment