我希望我的QT应用程序检查sourceforge.net上是否有更新。为此,我使用了请求:https://sourceforge.net/projects/kidbasic/best_release.json 如果您将此链接用于浏览器,您将获得一些json回复。 所以,这是代码:
app.pro
QT += core gui
QT += network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = app
TEMPLATE = app
SOURCES += main.cpp\
mainwindow.cpp
HEADERS += mainwindow.h
的main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QPushButton>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void replyFinished(QNetworkReply* reply);
void checkForUpdate(void);
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QWidget * wdg = new QWidget(this);
QPushButton *train_button = new QPushButton(wdg);
train_button->setText(tr("check update"));
setCentralWidget(wdg);
QObject::connect(train_button, SIGNAL(released()), this, SLOT(checkForUpdate()));
}
MainWindow::~MainWindow(){ }
void MainWindow::checkForUpdate(void){
QNetworkRequest request;
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QSslConfiguration config = QSslConfiguration::defaultConfiguration();
config.setProtocol(QSsl::SecureProtocols);
request.setSslConfiguration(config);
request.setUrl(QUrl("https://sourceforge.net/projects/kidbasic/best_release.json"));
//other urls to test
//request.setUrl(QUrl("https://sourceforge.net/projects/openofficeorg.mirror/files/stats/json?start_date=2014-10-29&end_date=2014-11-04"));
//request.setUrl(QUrl("https://ro.gravatar.com/205e460b479e2e5b48aec07710c08d50.json"));
//request.setUrl(QUrl("http://headers.jsontest.com/"));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
manager->get(request);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
}
void MainWindow::replyFinished(QNetworkReply* reply){
qDebug() << reply->error();
if(reply->error() == QNetworkReply::NoError) {
//process json reply
QString strReply = (QString)reply->readAll();
qDebug() << strReply;
} else {
qDebug() << "ERROR";
}
reply->deleteLater();
}
(为了让它在没有警告的情况下工作,我从https://indy.fulgan.com/SSL/获取libeay32.dll
和ssleay32.dll
并将这些文件放在我的应用程序的同一文件夹中 - 因为https
)。
如果我尝试其他网址,我会得到正确答复。如果我使用任何surceforge.net
请求,则会收到此错误:QNetworkReply::NetworkError(RemoteHostClosedError)
。
我使用https://www.hurl.it发出相同的请求,一切似乎都没问题。我也使用https://httpstatus.io/获得了相同的结果。
如何通过QT获得surceforge.net
的有效回复?
答案 0 :(得分:1)
sourceforge.net
时, Mozilla/5.0
似乎正在关闭连接(这是QNetworkAccessManager
在没有QNetworkRequest::UserAgentHeader
时使用的默认用户代理设定)。
您可能必须在发送请求之前设置自定义用户代理:
request.setHeader(QNetworkRequest::UserAgentHeader, "App/1.0");