Qt QNetworkAccessManager & simple Web service return



我有一个简单的web服务,URL如下:

http://localhost:8080/WebSvc1/webresources/generic/data?ctype=Ping

返回一个简单的XML数据:

<CALL TYPE='Ping'><IP>10.0.0.10</IP></CALL>

我正在试着写一个Qt程序来调用这个web服务。

调用的代码如下:

  QUrl qrl("http://localhost:8080/WebSvc1/webresources/generic/data?ctype=Ping");
  manager = new QNetworkAccessManager(this);
  connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
  printf ("Calling url: [%s]n", qPrintable(url));
  QNetworkReply *reply = 0;
  reply = manager->get(QNetworkRequest(qrl));
  qDebug() << reply->readAll();

我期待/希望readAll将获得XML文本数据并打印它(通过qDebug)。

我什么也没看到,程序就挂起了。

更新,也有这个:

void obj::replyFinished(QNetworkReply *reply)
{
qDebug() << reply->readAll();
}

我已经提供了一个示例(强制同步请求<->应答交换以简化调试过程),它应该适合您:

QUrl qrl("http://localhost:8080/WebSvc1/webresources/generic/data?ctype=Ping");
qDebug() << "Calling url: " << qrl.toString();
manager = new QNetworkAccessManager();
QNetworkReply* reply = manager->get(QNetworkRequest(qrl));
QEventLoop eventLoop;
connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
eventLoop.exec();
if (reply->error() != QNetworkReply::NoError)
{
    qDebug() << "Network error: " << reply->error();
}
else
{
    qDebug() << reply->readAll();
}

注意,finished信号的"发射极"不是QNetworkAccessManager,而是reply本身。

我认为您的错误可能与您的web服务有关。我尝试了你的代码(稍微修改)与httpbin.org,并得到适当的答复。也许你可以用httpbin.org看看你的代码,然后看看你是否可以追踪到你的服务出了什么问题。

MainWindow.cpp

#include "MainWindow.hpp"
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QDebug>
MainWindow::MainWindow(QWidget* parent)
  : QMainWindow(parent), manager(this) {
  load();
}
void MainWindow::load() {
  const QUrl url(QStringLiteral("http://httpbin.org/xml"));
  QNetworkReply* reply = manager.get(QNetworkRequest(url));
  connect(reply, &QNetworkReply::finished, this, [this, reply]() {
    replyFinished(reply);
  });
  qDebug() << reply->readAll(); // The reply won't be ready by now, so
                                // testing here isn't very helpful.
}
void MainWindow::replyFinished(QNetworkReply* reply) {
  qDebug() << reply->readAll();
  reply->deleteLater();
}

MainWindow.hpp

#ifndef MAINWINDOW_HPP
#define MAINWINDOW_HPP
#include <QMainWindow>
#include <QNetworkAccessManager>
#include <QNetworkReply>
class MainWindow : public QMainWindow {
  Q_OBJECT
 public:
  explicit MainWindow(QWidget* parent = nullptr);
 public slots:
  void load();
  void replyFinished(QNetworkReply* reply);
 private:
  QNetworkAccessManager manager;
};
#endif // MAINWINDOW_HPP

main.cpp

#include "MainWindow.hpp"
#include <QApplication>
int main(int argc, char* argv[]) {
  QApplication a(argc, argv);
  MainWindow w;
  w.show();
  return a.exec();
}

network.pro

QT += core gui widgets network
TARGET = network
TEMPLATE = app
DEFINES += QT_DEPRECATED_WARNINGS
CONFIG += c++11
SOURCES += 
  main.cpp 
  MainWindow.cpp
HEADERS += MainWindow.hpp

相关内容

  • 没有找到相关文章

最新更新