MFC中调用web api

使用COM组件来调用,需要catch com error.

IXMLHTTPRequestPtr pIXMLHTTPRequest = NULL;

BSTR bstrString = NULL;

HRESULT hr;

 

try {

hr=pIXMLHTTPRequest.CreateInstance("Msxml2.XMLHTTP.6.0");

SUCCEEDED(hr) ? 0 : throw hr;

 

hr=pIXMLHTTPRequest->open("POST", "<web api URL>", false);

 

pIXMLHTTPRequest->setRequestHeader("Content-Type","application/json;charset=utf-8");

SUCCEEDED(hr) ? 0 : throw hr;

 

wchar_t keyToSend[256];

swprintf( keyToSend, L"{"aa":"%s", "Password":"%s"}",<varible 1>, <varible 2>);

 

hr=pIXMLHTTPRequest->send(keyToSend);

SUCCEEDED(hr) ? 0 : throw hr;

 

bstrString=pIXMLHTTPRequest->responseText;

std::wstring result(bstrString);

 

if( result.compare(L""OK"") == 0)

{

return 0;

}

else

{

    return 1;

}

      

} catch (const std::exception& e) {

WriteLog( e.what());

if(bstrString)

::SysFreeString(bstrString);

     return 2;

}

catch (const _com_error& e)

{

wchar_t errormessage[1024];

swprintf( errormessage, 500, L"%s", e.ErrorMessage() );

WriteLog( errormessage);

 

if(bstrString)

::SysFreeString(bstrString);

     return 2;

      

}

 

用上述代码,调用有的启用了 SSL的web api时会报COM错误: The download of the specified resource has failed

然后查了一下文章,建议用ServerXMLHTTP对象,这个好像是专门给service api用的,于是把代码中的COM组件换成这个:

hr=pIXMLHTTPRequest.CreateInstance("Msxml2.XMLHTTP.6.0");

 

果然原来有问题的调用都成功了。

这里有关于这个COM 组件的使用方法: https://msdn.microsoft.com/en-us/library/ms766431(v=vs.85).aspx

另外注意调用任何COM组件的时候组件的名字都不能写错,否则程序会直接崩溃。

原文地址:https://www.cnblogs.com/time-is-life/p/6892902.html