我在简单的http客户端中有简单的请求方法,即QRunnble worker正在调用 请求的所有返回者都是状态0, 我在几次测试之后发现了什么,当我给应用程序运行1个线程时 只有1个网址处理其工作正常,我得到状态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);
}
为什么它总是失败?