从 VC++6.0 调用 WebService






3.87/5 (5投票s)
适用于希望从 VC6.0 调用 WebService 的初学者。
引言
这篇文章对那些从未进行过从 VC++ 调用 WebService 的操作,并且想知道如何发送请求并获取响应的人很有用。这是我为了学习目的而创建的第一个应用程序。
背景
我参考了一篇 CodeProject 文章。要调用 WebService,我们需要两件事:一是必须在调用之前创建 WebService,二是这个调用它的 VC++ 应用程序。
Using the Code
首先,我想简要介绍一下如何创建 WebService。我是一名系统开发人员,因此我对创建 Webservice 的了解不够好。您需要启动 Visual 2005,然后选择 文件 -> 新建 -> 网站 -> ASP.NET webservice。然后浏览器会创建一个默认函数。在该函数内部,您需要编写一些您想要作为请求接收并根据输入返回内容的函数。我将名称作为输入,并根据输入名称返回地址。这就是为什么您可以在我发布的 XML 代码中看到 Chaitanya 这个名称。创建 WebService 后,您需要发布您的站点(您可以使用 Inet 管理器来完成)。
这是我用来发布请求并从 WebService 获取响应的代码。
//
// Any source code blocks look like this
//
IXMLHttpRequestPtr httpReq( _uuidof(MyXMLHTTPRequest));
_bstr_t HTTPMethod ;
_variant_t noAsync = _variant_t( (bool)false );
//httpReq.CreateInstance("MyXMLHTTPRequest");
CString strUserName = "mahesh"; // this one is user name of webservice machine
VARIANT vUser;
vUser.vt = VT_BSTR;
vUser.bstrVal = strUserName.AllocSysString();
CString strPass = "gtl=11"; // this is system password
VARIANT vPassword;
vPassword.vt = VT_BSTR;
vPassword.bstrVal = strPass.AllocSysString();
HTTPMethod = _bstr_t( "POST" );
// http://gtl-334/XmlTesting/Service.asmx this is url as webservice.
httpReq->open(HTTPMethod ,
"http://gtl-334/XmlTesting/Service.asmx",noAsync,vUser,vPassword);
httpReq->setRequestHeader("Content-Type", "application/soap+xml");
CString szRequest;
szRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?> \
<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"
xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\"> \
<soap12:Body>\
<HelloWorld xmlns=\"http://tempuri.org/\"> \
<strUserName>Chaitanya</strUserName>\
</HelloWorld>\
</soap12:Body>\
</soap12:Envelope>";
VARIANT vRequest;
vRequest.vt = VT_BSTR;
vRequest.bstrVal = szRequest.AllocSysString();
httpReq->send(vRequest); // sending to that URL
BSTR strText;
_bstr_t bsResponse = httpReq->responseText; //receiving reply from web service
AfxMessageBox(bsResponse);
CDialog::OnOK();
一件非常重要的事情是,我们需要导入 MSXML.dll,您可以在代码中的 stdafx.h 文件和文件中的 "using namespace MSXML;
" 行中看到。
关注点
您可以就如何改进这篇文章提出建议,以便我也能学习新知识。如果您有任何疑问,可以发布消息。我会尝试解决它,这样我也可以在这个领域学习新知识。您可以给我发邮件至 cha1202001@yahoo.com。
历史
- 2007 年 6 月 22 日:初始发布