我注意到QHttp
类在Qt5中不再可用,我一直收到一条错误消息,说我需要使用QNetworkAccessManager
来完成此操作。
有没有办法在Qt5中访问这个类?
在Qt 5中使用QNetworkAccessManager
。您可以使用事件循环等待,直到回复完成,然后读取可用字节:
QString My_class::My_Method()
{
QNetworkAccessManager manager;
QNetworkReply *reply = manager.get(QNetworkRequest(QUrl(myURL)));
QEventLoop loop;
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), &loop, SLOT(quit()));
loop.exec();
QByteArray bts = reply->readAll();
QString str(bts);
delete reply;
return str;
}
您也可以通过将QNetworkAccessManager
的finished
信号连接到一个插槽来以异步方式进行:
connect(&manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(onFinished(QNetworkReply*)));
并在那里读取数据:
void onFinished(QNetworkReply* reply)
{
if (reply->error() == QNetworkReply::NoError)
{
QByteArray bts = reply->readAll();
...
}
}
这是一个简单的HTTP帖子(我使用的是Qt 5.3.2)
int Connection::postRequest(QString requestType, QUrl params){
QString params_array = params.query();
QNetworkRequest request(user->url);
request.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(params_array.size()));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QEventLoop waitLoop;
QNetworkAccessManager* connection = new QNetworkAccessManager(/*`this` can also be passed*/);
QNetworkReply* reply = connection->post(request, params_array.toUtf8());
QObject::connect(reply, SIGNAL(finished()), &waitLoop, SLOT(quit()));
waitLoop.exec();
int errorCode = reply->error();
if (errorCode != 0){
// Show Error Message
}
else{
// Parse "reply"
}
delete reply;
delete connection;
return errorCode;
}
假设您不需要维护庞大的代码库,正确的方法是使用新的QNetworkAccessManager类。