0

我在我的应用程序 qml 中添加了一个 Web 浏览器,但我无法连接到需要证书的网站。因为当我添加网站时,我得到一个白页。请帮帮我。

谢谢你。

4

1 回答 1

2

要与使用不受信任证书的网站进行通信,您应该向 QDeclarativeEngine 提供您自己的 NetworkManagerFactory,如下所示。此外,这种技术将帮助您监控在任何其他情况下您的网络请求出了什么问题。

class WebViewNetworkManagerFactory
  : public QObject
  , public QDeclarativeNetworkAccessManagerFactory
{
  Q_OBJECT

public:
  explicit WebViewNetworkManagerFactory(QObject *parent = 0)
    : QObject(parent)
  {}

public: // QDeclarativeNetworkAccessManagerFactory
  QNetworkAccessManager *create(QObject *parent) {
    QNetworkAccessManager *networkAccessManager = new QNetworkAccessManager(parent);
    connect(networkAccessManager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
            this, SLOT(onSslErrors(QNetworkReply*,QList<QSslError>)));
    connect(networkAccessManager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(onReplyFinished(QNetworkReply*)));
    return networkAccessManager;
  }

private slots:
  void onSslErrors(QNetworkReply *reply, const QList<QSslError> &errors) {
    qDebug("onSslErrors");
    reply->ignoreSslErrors(errors);
  }

  void onReplyFinished(QNetworkReply *reply) {
    Q_ASSERT(reply); if (!reply) return;
    if (reply->error() == QNetworkReply::NoError) {
      return;
    }
    const int httpStatusCode = reply->attribute(
      QNetworkRequest::HttpStatusCodeAttribute).toInt();
      qDebug(QString("Network error = %1, HTTP code = %2, error description = '%3'")
               .arg(reply->error())
               .arg(httpStatusCode)
               .arg(reply->errorString())
               .toAscii());
  }
};

在代码中的某处使用,您可以在其中创建根 DeclarativeView:

QDeclarativeView *buildRootView() {
  QScopedPointer<QDeclarativeView> view(new QDeclarativeView());
  QObject::connect(view->engine(), SIGNAL(quit()),
                   view.data(), SLOT(close()));
  view->engine()->setNetworkAccessManagerFactory(
    new WebViewNetworkManagerFactory(view.data()));
  // other initialization stuff...
  return view.take();
}
于 2012-08-22T07:31:21.403 回答