请用qt写出get请求带请求头的代码
时间: 2023-05-13 22:05:06 浏览: 140
python requests.get带header
5星 · 资源好评率100%
以下是使用 Qt 发送带请求头的 GET 请求的示例代码:
```cpp
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QNetworkAccessManager manager;
QNetworkRequest request(QUrl("https://www.example.com"));
request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
request.setRawHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
QNetworkReply *reply = manager.get(request);
QObject::connect(reply, &QNetworkReply::finished, [&](){
if(reply->error() == QNetworkReply::NoError){
qDebug() << "Success: " << reply->readAll();
}else{
qDebug() << "Error: " << reply->errorString();
}
reply->deleteLater();
a.quit();
});
return a.exec();
}
```
这段代码使用 QNetworkAccessManager 类发送了一个 GET 请求,并设置了请求头 User-Agent 和 Accept。如果请求成功,将会输出响应内容;如果请求失败,将会输出错误信息。
阅读全文