[英]HTTP POST request in QT using QNetworkAccessManager
I have to send a data string to my server I am desperately trying with QNetworkAccessManager but for weeks yet no success can somebody please help!我必须向我的服务器发送一个数据字符串我正在拼命尝试使用 QNetworkAccessManager 但几个星期以来都没有成功,有人可以帮忙!
My codes are given below.我的代码如下。
it compiles but when I run it I get an empty reply.它编译但是当我运行它时我得到一个空的答复。
QT application output: I get an empty reply QT 应用程序输出:我得到一个空回复
When I check the log file on the server which receives the text it is empty.当我检查接收文本的服务器上的日志文件时,它是空的。
I tried using POSTMAN it works fine.我尝试使用 POSTMAN 它工作正常。
please check the following image it shows the result when I tried with POSTMAN请检查下图,它显示了我尝试使用 POSTMAN 时的结果
The result using POSTMAN使用POSTMAN的结果
I have included my code below, please help.我在下面包含了我的代码,请帮忙。
Main program主程序
#include <QCoreApplication>
#include <stdio.h>
#include <string>
#include <QtDebug>
#include <QObject>
#include <httpmanager.h>
QByteArray dataString ="A=##1802201049565471101000000N0526.874000E07256.4380000101035070#&11397002170466466466466466&12208004230370336441514488!~~~0";
using namespace std;
int main(void)
{
HTTPmanager myHttpManager;
while(1){
myHttpManager.postData("A==##1802201049565471101000000N0526.874000E07256.4380000101035070#&11397002170466466466466466&12208004230370336441514488!~~~0");
Sleep(1000);
}//main loop ends
return 0;
}
httpmanager.h------- httpmanager.h-------
#ifndef HTTPMANAGER_H
#define HTTPMANAGER_H
#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QUrl>
class HTTPmanager : public QObject
{
Q_OBJECT
public:
HTTPmanager();
~HTTPmanager();
void postData(QString str);
private:
QNetworkAccessManager * manager;
QNetworkRequest request;
QNetworkReply *reply;
private slots:
void replyFinished(QNetworkReply *rep);
};
#endif // HTTPMANAGER_H
httpmanager.cpp------------- httpmanager.cpp------------
#include "httpmanager.h"
HTTPmanager::HTTPmanager()
{
}
HTTPmanager::~HTTPmanager()
{
delete manager; manager = nullptr;
}
void HTTPmanager::postData(QString str)
{
QByteArray data = str.toUtf8();
QUrl url;
manager = new QNetworkAccessManager(this);
url.setScheme("http");
url.setHost("test.vivcorefmms.com");
url.setPath("/node/filter_data");
request.setUrl(url);
request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRawHeader("Content-Length", QByteArray::number(data.size()));
//connect(reply, SIGNAL(readyRead()),this, SLOT(slotReadyRead()));
connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));
//connect(reply, SIGNAL(sslErrors(QList<QSslError>)),this, SLOT(slotSslErrors(QList<QSslError>)));
//connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
//loop.exec();
reply = manager->post(request,data);
QByteArray bts = reply->readAll();
QString tmp(bts);
qDebug() << "Reply:"<<tmp;
}
void HTTPmanager::replyFinished(QNetworkReply *rep)
{
QByteArray bts = rep->readAll();
QString str(bts);
qDebug() << "Reply:"<<str;
}
It seems that you do not know the following concepts:看来你不知道以下几个概念:
Qt Network like all Qt modules work asynchronously so don't think about getting the information synchronously. Qt Network 像所有 Qt 模块一样异步工作,所以不要考虑同步获取信息。
Qt needs an eventloop, in this case QCoreApplication is enough. Qt 需要一个事件循环,在这种情况下 QCoreApplication 就足够了。
If you want to do periodic tasks then you should use a QTimer instead of a while loop with Sleep.如果您想执行周期性任务,那么您应该使用 QTimer 而不是带有 Sleep 的 while 循环。
Considering the above, the solution is:综上所述,解决方法是:
httpmanager.h httpmanager.h
#ifndef HTTPMANAGER_H
#define HTTPMANAGER_H
#include <QObject>
class QNetworkReply;
class QNetworkAccessManager;
class HTTPManager : public QObject
{
Q_OBJECT
public:
HTTPManager(QObject *parent=nullptr);
~HTTPManager();
void postData(QString str);
private Q_SLOTS:
void replyFinished(QNetworkReply *rep);
private:
QNetworkAccessManager * manager;
QNetworkReply *reply;
};
#endif // HTTPMANAGER_H
httpmanager.cpp httpmanager.cpp
#include "httpmanager.h"
#include <QNetworkAccessManager>
#include <QNetworkReply>
HTTPManager::HTTPManager(QObject *parent)
: QObject(parent), manager(new QNetworkAccessManager(this))
{
connect(manager, &QNetworkAccessManager::finished,this, &HTTPManager::replyFinished);
}
HTTPManager::~HTTPManager()
{
}
void HTTPManager::postData(QString str)
{
QNetworkRequest request;
QByteArray data = str.toUtf8();
QUrl url;
url.setScheme("http");
url.setHost("test.vivcorefmms.com");
url.setPath("/node/filter_data");
request.setUrl(url);
request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
manager->post(request, data);
}
void HTTPManager::replyFinished(QNetworkReply *rep)
{
QByteArray bts = rep->readAll();
QString str = QString::fromUtf8(bts);
qDebug().noquote() << "Reply:"<<str;
rep->deleteLater();
}
main.cpp主程序
#include "httpmanager.h"
#include <QCoreApplication>
#include <QTimer>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
HTTPManager manager;
QTimer timer;
timer.setInterval(1000);
QObject::connect(&timer, &QTimer::timeout, [&manager](){
manager.postData("A==##1802201049565471101000000N0526.874000E07256.4380000101035070#&11397002170466466466466466&12208004230370336441514488!~~~0");
});
timer.start();
return a.exec();
}
Reply: <head><title>Not Acceptable!</title></head><body><h1>Not Acceptable!</h1><p>An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security.</p></body></html>
And that is caused because a user-agent is missing so modifying it to:这是因为缺少用户代理,因此将其修改为:
request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRawHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36");
manager->post(request, data);
Obtaining the following:获取以下内容:
Reply: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Database Error</title>
<style type="text/css">
::selection { background-color: #E13300; color: white; }
::-moz-selection { background-color: #E13300; color: white; }
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
padding: 14px 15px 10px 15px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#container {
margin: 10px;
border: 1px solid #D0D0D0;
box-shadow: 0 0 8px #D0D0D0;
}
p {
margin: 12px 15px 12px 15px;
}
</style>
</head>
<body>
<div id="container">
<h1>A Database Error Occurred</h1>
<p>Error Number: 1048</p><p>Column 'node_id' cannot be null</p><p>INSERT INTO `node_info` (`node_info_id`, `node_id`, `message_id`, `gsm`, `wifi`, `gprs`, `_3g`, `bluetooth`, `gps`, `emergency_code`, `env_temperature`, `env_humidity`, `env_pressure`, `gps_speed`, `gps_latitude`, `gps_longitude`, `date`, `time`, `number_of_compartment`, `number_of_dispense`, `sys_date`, `sys_time`) VALUES ('', NULL, '654', '7', '0', '1', '1', '1', '0', '0', '03', '507', '0101', '0', NULL, NULL, '#18022', '010495', 15, '', '2020-03-28', '23:31:10')</p><p>Filename: models/Model_master.php</p><p>Line Number: 156</p> </div>
</body>
</html>
And the message points out the error:该消息指出了错误:
Error Number: 1048
Column 'node_id' cannot be null
INSERT INTO `node_info` (`node_info_id`, `node_id`, `message_id`, `gsm`, `wifi`, `gprs`, `_3g`, `bluetooth`, `gps`, `emergency_code`, `env_temperature`, `env_humidity`, `env_pressure`, `gps_speed`, `gps_latitude`, `gps_longitude`, `date`, `time`, `number_of_compartment`, `number_of_dispense`, `sys_date`, `sys_time`) VALUES ('', NULL, '654', '7', '0', '1', '1', '1', '0', '0', '03', '507', '0101', '0', NULL, NULL, '#18022', '010495', 15, '', '2020-03-28', '23:18:26')
Filename: models/Model_master.php
Line Number: 156
Which shows an error caused by the data sent that seems not to comply with the processing, that is, A==##1802201049565471101000000N0526.874000E07256.4380000101035070#&11397002170466466466466466&12208004230370336441514488!~~~0
that seems to be not well formed这说明造成的数据错误发送,这似乎不符合的处理,即,
A==##1802201049565471101000000N0526.874000E07256.4380000101035070#&11397002170466466466466466&12208004230370336441514488!~~~0
,这似乎是没有很好地形成
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.