問題描述
我想查看 GET 請求的結果.根據我的理解,這段代碼應該可以做到.我做錯了什么?
I want to see the results of a GET request. By my understanding, this code should do it. What am I doing wrong?
void getDoc::on_pushButton_2_clicked()
{
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
manager->get(QNetworkRequest(QUrl("http://www.google.com")));
}
void getDoc::replyFinished(QNetworkReply *reply)
{
qDebug() << reply->error(); //prints 0. So it worked. Yay!
QByteArray data=reply->readAll();
qDebug() << data; // This is blank / empty
QString str(data);
qDebug() << "Contents of the reply: ";
qDebug() << str; //this is blank or does not print.
}
代碼編譯并運行良好.它只是不起作用.
The code compiles and runs fine. It just doesn't work.
推薦答案
嘗試將您的回復已完成槽修改為如下所示:
Try modifying your replyFinished slot to look like this:
QByteArray bytes = reply->readAll();
QString str = QString::fromUtf8(bytes.data(), bytes.size());
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
然后您可以打印 statusCode 以查看是否收到 200 響應:
You can then print the statusCode to see if you are getting a 200 response:
qDebug() << QVariant(statusCode).toString();
如果您收到 302 響應,您將收到狀態重定向.你需要像這樣處理它:
If you are getting a 302 response, you are getting a status redirect. You will need to handle it like this:
if(statusCode == 302)
{
QUrl newUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
qDebug() << "redirected from " + replyUrl + " to " + newUrl.toString();
QNetworkRequest newRequest(newUrl);
manager->get(newRequest);
return;
}
我在遇到狀態碼 302 時返回,因為我不想執行其余的方法.
I'm returning when encountering a status code of 302 since I don't want the rest of the method to execute.
我希望這會有所幫助!
這篇關于Qt QNetworkReply 始終為空的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!