从网上查找Qt调用WebService的方案,需要下载三方的类库,而且需要使用好几个控制台命令,才能生成代理客户端类.因为只是简单的测试,没有采用这种方式,直接使用HTTP的Get获取网站内容,也非常简单,调用开放的翻译WebService接口.代码如下:
QEventLoop loop;//事件循环对象,在任何时候,你都可以创建一个QEventLoop的对象,然后调用它的exec() 来开始一个局部的事件循环。
QNetworkAccessManager manager(this);//QHTTP等类都过时了,推荐使用这个类实现网络通信
QString sUrl = transUrl + ui.leChinese->text();//生成HTTP的URL地址
QUrl::toPercentEncoding(sUrl);//进行url编码
QNetworkReply *reply = manager.get(qnetworkrequest(sUrl));//调用get方法获取WebService返回的xml
QObject::connect(reply,SIGNAL(finished()),&loop,SLOT(quit())); //调用返回后事件循环对象退出
//开启子事件循环 等待调用返回
loop.exec();
QFile file(TRANSFILENAME);
file.open(qiodevice::writeonly);
QTextStream out(&file);
out.setCodec("UTF8");//指定文件的编码,否则文件中的中文乱码
QTextCodec *codec = QTextCodec::codecForName("UTF8");
out << codec->toUnicode(reply->readAll()) << endl;//从HTTP请求响应对象中读取xml文件内容,并存入到文件
file.close();
QFile xmlfile(TRANSFILENAME);
if(!xmlfile.open(QFile::ReadOnly | QFile::Text)) return;
QTextStream floStream(&xmlfile);
floStream.setCodec(codec);
QString xmlData = floStream.readAll();
xmlfile.close();
QDomDocument doc;//创建Dom类对象解析xml
QString errorInfo;
int errorLine,errorColumn;
if(doc.setContent(xmlData))
{
QDomNode node = doc.documentElement().elementsByTagName("diffgr:diffgram").at(0);
node = node.toElement().elementsByTagName("Dictionary").at(0);
node = node.toElement().elementsByTagName("Translation").at(0);
ui.leResult->setText(node.toElement().text());//得到xml中某个节点的值
}
xmlfile.close();
QEventLoop loop;//事件循环对象,在任何时候,你都可以创建一个QEventLoop的对象,然后调用它的exec() 来开始一个局部的事件循环。
QNetworkAccessManager manager(this);//QHTTP等类都过时了,推荐使用这个类实现网络通信
QString sUrl = transUrl + ui.leChinese->text();//生成HTTP的URL地址
QUrl::toPercentEncoding(sUrl);//进行url编码
QNetworkReply *reply = manager.get(qnetworkrequest(sUrl));//调用get方法获取WebService返回的xml
QObject::connect(reply,SIGNAL(finished()),&loop,SLOT(quit())); //调用返回后事件循环对象退出
//开启子事件循环 等待调用返回
loop.exec();
QFile file(TRANSFILENAME);
file.open(qiodevice::writeonly);
QTextStream out(&file);
out.setCodec("UTF8");//指定文件的编码,否则文件中的中文乱码
QTextCodec *codec = QTextCodec::codecForName("UTF8");
out << codec->toUnicode(reply->readAll()) << endl;//从HTTP请求响应对象中读取xml文件内容,并存入到文件
file.close();
QFile xmlfile(TRANSFILENAME);
if(!xmlfile.open(QFile::ReadOnly | QFile::Text)) return;
QTextStream floStream(&xmlfile);
floStream.setCodec(codec);
QString xmlData = floStream.readAll();
xmlfile.close();
QDomDocument doc;//创建Dom类对象解析xml
QString errorInfo;
int errorLine,errorColumn;
if(doc.setContent(xmlData))
{
QDomNode node = doc.documentElement().elementsByTagName("diffgr:diffgram").at(0);
node = node.toElement().elementsByTagName("Dictionary").at(0);
node = node.toElement().elementsByTagName("Translation").at(0);
ui.leResult->setText(node.toElement().text());//得到xml中某个节点的值
}
xmlfile.close();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。