Qt调用WebService

来源:互联网 发布:mysql 数据库建模 编辑:程序博客网 时间:2024/06/06 06:40
 从网上查找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();
原创粉丝点击