簡述
Qt本身給我們提供了調用WebService的解決方案QtSoap,源碼及示例見:qt-solutions-qtsoap
下載編譯
下載源碼后,需要修改一些地方(我的版本是Qt5),按照錯誤提示修改即可,很簡單。
編譯完成之后會生成QtSolutions_SOAP-headd.lib、QtSolutions_SOAP-headd.dll。。。
使用
拷貝QtSolutions_SOAP-headd.lib至lib目錄下,拷貝qtsoap.h至include目錄下。
pro中添加庫文件及庫目錄:
INCLUDEPATH += $$PWD/include
LIBS += -L$$PWD/lib -lQtSolutions_SOAP-headd
實例解析
下面,我們以“獲得騰訊QQ在線狀態”為例,見:WebXml.com.cn,里面包含了大量的Web服務,例如:手機號碼歸屬地查詢,電子郵件地址驗證、城市天氣預報查詢等。
示例
SOAP 1.1
以下是SOAP1.1請求和響應示例。所顯示的占位符需替換為實際值。
效果
源碼
// 構建控件
m_pQQLabel = new QLabel(this);
m_pStateLabel = new QLabel(this);
m_pQQLineEdit = new QLineEdit(this);
m_pStateLineEdit = new QLineEdit(this);
m_pSubmitButton = new QPushButton(this);
m_pStateLineEdit->setReadOnly(true);
m_pQQLabel->setText(QString::fromLocal8Bit("QQ號碼:"));
m_pStateLabel->setText(QString::fromLocal8Bit("QQ狀態:"));
m_pSubmitButton->setText(QString::fromLocal8Bit("提交"));
QGridLayout *pLayout = new QGridLayout();
pLayout->addWidget(m_pQQLabel, 0, 0);
pLayout->addWidget(m_pQQLineEdit, 0, 1);
pLayout->addWidget(m_pStateLabel, 1, 0);
pLayout->addWidget(m_pStateLineEdit, 1, 1);
pLayout->addWidget(m_pSubmitButton, 2, 1, 1, 1, Qt::AlignRight);
pLayout->setSpacing(10);
pLayout->setContentsMargins(10, 10, 10, 10);
setLayout(pLayout);
// 連接信號槽
m_pHttp = new QtSoapHttpTransport(this);
connect(m_pSubmitButton, SIGNAL(clicked()), this, SLOT(onSubmit()));
connect(m_pHttp, SIGNAL(responseReady(const QtSoapMessage &)), this, SLOT(onResponse(const QtSoapMessage &)));
// 提交請求
void MainWindow::onSubmit()
{
QtSoapMessage message;
// 設置方法
message.setMethod("qqCheckOnline", "http://WebXml.com.cn/");
// 設置動作
m_pHttp->setAction("http://WebXml.com.cn/qqCheckOnline");
// 設置主機
m_pHttp->setHost("www.webxml.com.cn");
// 添加方法參數
QString strQQ = m_pQQLineEdit->text();
message.addMethodArgument("qqCode", "", strQQ);
QString strXML = message.toXmlString();
// 提交請求
m_pHttp->submitRequest(message, "/webservices/qqOnlineWebService.asmx");
}
void MainWindow::onResponse(const QtSoapMessage &response)
{
QString strXML = response.toXmlString();
QDomDocument doc;
doc.setContent(strXML);
// 接在在線狀態
QDomNodeList nodeList = doc.elementsByTagName("qqCheckOnlineResult");
if (!nodeList.isEmpty())
{
QDomNode node = nodeList.at(0);
QString strResult = node.toElement().text();
QString strState("N/A");
if (QString::compare(strResult, "Y") ==0)
{
strState = QString::fromLocal8Bit("在線");
}
else if (QString::compare(strResult, "N") == 0)
{
strState = QString::fromLocal8Bit("離線");
}
else if (QString::compare(strResult, "E") == 0)
{
strState = QString::fromLocal8Bit("QQ號碼錯誤");
}
else if (QString::compare(strResult, "A") == 0)
{
strState = QString::fromLocal8Bit("商業用戶驗證失敗");
}
else if (QString::compare(strResult, "V") == 0)
{
strState = QString::fromLocal8Bit("免費用戶超過數量");
}
m_pStateLineEdit->setText(strState);
}
}
我們也可以使用qq號碼進行在線驗證:qqCheckOnline