我在简单的 http 客户端中有简单的请求方法,QRunnble 工作人员正在调用请求的所有返回者状态为 0,经过几次测试后我发现的更多是,当我让应用程序使用 1 个
只有 1 个 url 的线程运行时处理它的工作正常,我得到状态 200 。我怀疑我的http客户端代码中的某些东西已经磨损并且不支持多线程模式这是我完整的httpclient代码:
这是请求的代码:
#ifndef _HttpClient_
#define _HttpClient_
#include <QNetworkAccessManager>
#include <QtNetwork>
#include <QUrl>
QT_BEGIN_NAMESPACE
class QSslError;
class QAuthenticator;
class QNetworkReply;
QT_END_NAMESPACE
class HttpClient : public QObject
{
Q_OBJECT
public:
HttpClient(QFile* file,QMutex* mutex);
~HttpClient();
void startRequest(QString& url);
public slots:
#ifndef QT_NO_OPENSSL
void sslErrors(QNetworkReply*,const QList<QSslError> &errors);
#endif
private:
QString m_sUrl;
QUrl m_url;
QNetworkAccessManager* m_networkManager;
QNetworkReply *reply;
int httpGetId;
void HandleNetworkError(QNetworkReply::NetworkError& networkError,
QNetworkReply *networkReply);
};
#endif
------------------------------------
#include "HttpClient.h"
#include <QMutexLocker>
#include <QTextStream>
HttpClient::HttpClient()
{
m_networkManager = new QNetworkAccessManager(this);
}
HttpClient::~HttpClient()
{
;
}
void HttpClient::startRequest(QString& url)
{
QNetworkRequest request;
request.setUrl(QUrl(url));
QEventLoop loop;
reply = m_networkManager->get(request);
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
LOG_MSG("Is UrlAlive?:"+url.toStdString())
QString ApiResponse;
QByteArray data=reply->readAll();
ApiResponse.append(QString::fromUtf8(data));
int iStatusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (reply->error()) {
QNetworkReply::NetworkError networkError = reply->error();
HandleNetworkError(networkError,reply);
}
QString s = QString::number(iStatusCodeV);
reply->deleteLater();
reply = 0;
}
void HttpClient::HandleNetworkError(QNetworkReply::NetworkError& networkError,QNetworkReply *networkReply)
{
if(networkError != QNetworkReply::NoError)
{
QString err = networkReply->errorString();
LOG_MSG("HttpClient::HandleNetworkError:"+err.toStdString());
}
}
#ifndef QT_NO_OPENSSL
void HttpClient::sslErrors(QNetworkReply*,const QList<QSslError> &errors)
{
reply->ignoreSslErrors();
}
#endif
所有这些都是从 QRunnble 方法调用的,如下所示:
void ThreadWorker::run()
{
QMutexLocker lock(_m);
startwork();
lock.unlock();
}
void ThreadWorker::startwork()
{
m_pHttpClient = new HttpClient();
//each thread gets unique url
m_pHttpClient->startRequest(m_url);
}
为什么它总是失败?