C++ 如何编写 Qt HTTP GET 请求?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46943134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I write a Qt HTTP GET request?
提问by Alessandro95
I'd like to write a small HTTP GET
request in C++ but I'm not finding a solution.
我想GET
用 C++编写一个小的 HTTP请求,但我没有找到解决方案。
Maybe I have to use QNetworkAccessManager
class but I'm not an expert in C++ and it's really hard to understand something about this class.
也许我必须使用QNetworkAccessManager
类,但我不是 C++ 专家,而且很难理解这个类。
I have an URL to fetch, which will give me a JSON response; I have to extract a single key (key2
) and put the value in a variable. This is an example:
我有一个要获取的 URL,它会给我一个 JSON 响应;我必须提取一个键 ( key2
) 并将值放入变量中。这是一个例子:
{"key1": "value1", "key2": "**value2**", "key3": "value3"}
This is my debug code:
这是我的调试代码:
char value[20]
value = <**value2**>
After this I have to print this value in a form .ui
在此之后,我必须以 .ui 形式打印此值
回答by Tazo leladze
You need three things:
你需要三样东西:
QNetworkAccessManager * manager;
-> To send us a request.QNetworkRequest request;
-> what type of demand? get, post, ...QNetworkReply
. -> What's the answer?
QNetworkAccessManager * manager;
-> 向我们发送请求。QNetworkRequest request;
-> 什么类型的需求?获取,发布,...QNetworkReply
. -> 答案是什么?
for more detail:
欲知更多详情:
for example:
例如:
.cpp
.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
manager = new QNetworkAccessManager();
QObject::connect(manager, &QNetworkAccessManager::finished,
this, [=](QNetworkReply *reply) {
if (reply->error()) {
qDebug() << reply->errorString();
return;
}
QString answer = reply->readAll();
qDebug() << answer;
}
);
}
void MainWindow::on_pushButton_clicked()
{
request.setUrl(QUrl("http://url"));
manager->get(request);
}
MainWindow::~MainWindow()
{
delete ui;
delete manager;
}
.h file
.h 文件
private:
Ui::MainWindow *ui;
QNetworkAccessManager *manager;
QNetworkRequest request;
EDIT LAMBDA SLOT:if not use lambda SIGNAL SLOT.
编辑 LAMBDA 插槽:如果不使用 lambda 信号插槽。
Discribe one slot in your .h file for example:
描述 .h 文件中的一个插槽,例如:
private slots:
void managerFinished(QNetworkReply *reply);
in .cpp constructor replace lambda to
在 .cpp 构造函数中将 lambda 替换为
QObject::connect(manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(managerFinished(QNetworkReply*)));
now in your slot:
现在在您的插槽中:
void MainWindow::managerFinished(QNetworkReply *reply) {
if (reply->error()) {
qDebug() << reply->errorString();
return;
}
QString answer = reply->readAll();
qDebug() << answer;
}