gpt4 book ai didi

qt - Qt下的HTTP GET

转载 作者:可可西里 更新时间:2023-11-01 15:16:12 26 4
gpt4 key购买 nike

我有一个 n00b 问题,我似乎无法从我的 Qt 代码发出 HTTP GET 请求...

这里是应该工作的代码:

void MainWindow::requestShowPage(){
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(requestReceived(QNetworkReply*)));
manager->get(QNetworkRequest(QUrl("http://google.com")));
}

void MainWindow::requestReceived(QNetworkReply* reply){
QString replyText;
replyText.fromAscii(reply->readAll());

ui->txt_debug->appendPlainText(replyText);
}

但问题是这不起作用:在 requestReceived(QNetworkReply* reply) 中,replyText 似乎是空的,reply->error() 返回 0 并且 reply->errorString() 返回“未知错误”。我真的不知道现在该怎么办...

有什么想法吗?

最佳答案

明显有重定向,不认为是错误。
您应该使用回复属性中提供的重定向 url 运行新请求,直到获得真实页面:

void MainWindow::requestReceived(QNetworkReply *reply)
{
reply->deleteLater();

if(reply->error() == QNetworkReply::NoError) {
// Get the http status code
int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (v >= 200 && v < 300) // Success
{
// Here we got the final reply
QString replyText = reply->readAll();
ui->txt_debug->appendPlainText(replyText);
}
else if (v >= 300 && v < 400) // Redirection
{
// Get the redirection url
QUrl newUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
// Because the redirection url can be relative,
// we have to use the previous one to resolve it
newUrl = reply->url().resolved(newUrl);

QNetworkAccessManager *manager = reply->manager();
QNetworkRequest redirection(newUrl);
QNetworkReply *newReply = manager->get(redirection);

return; // to keep the manager for the next request
}
}
else
{
// Error
ui->txt_debug->appendPlainText(reply->errorString());
}

reply->manager()->deleteLater();
}

您还应该记录重定向的位置或计算重定向的次数,以避免永无止境的循环。

关于qt - Qt下的HTTP GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7218851/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com