前言
qt开发http通讯需要引入的模块与类
pro
QT += network
h
#include <QJsonObject>
#include <QJsonDocument>
#include <QNetworkAccessManager>
#include <QNetworkReply>
QNetworkAccessManager *manager;
cpp
manager = new QNetworkAccessManager(this);
connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinished(QNetworkReply*)));
具体实现
QNetworkRequest request;
QString url="http://"+hHost+":"+QString::number(postPort)+"/cctrl/Channel/equipmentState";
request.setUrl(QUrl(url));
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
request.setRawHeader("Content_Type","application/json");
QJsonObject logjson;
logjson.insert("gateNo",sSBBH);
logjson.insert("infraredState",yxzt.mid(0,1));
logjson.insert("videoState",yxzt.mid(1,1));
logjson.insert("organismsState",yxzt.mid(2,1));
logjson.insert("IPCState",yxzt.mid(3,1));
logjson.insert("frontDoorState",yxzt.mid(4,1));
logjson.insert("backDoorState",yxzt.mid(5,1));
logjson.insert("frontDoorIsOpen",yxzt.mid(6,1));
logjson.insert("backDoorIsOpen",yxzt.mid(7,1));
QImage img;
img.load(picPath+zjhm+"/zp.jpg");
QByteArray ba;
QBuffer buf(&ba);
img.save(&buf,"png",20);
QByteArray hexed=ba.toBase64();
QString pic(hexed);
buf.close();
logjson.insert("certImg",pic);
QJsonDocument doc;
doc.setObject(logjson);
QByteArray bdata=doc.toJson(QJsonDocument::Compact);
manager->post(request,bdata);
void Widget::replyFinished(QNetworkReply *reply)
{
if(reply->error()==QNetworkReply::NoError)
{
qDebug()<<"operation:"<<reply->operation();
qDebug()<<"status code:"<<reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
qDebug()<<"url:"<<reply->url();
const QByteArray reply_data=reply->readAll();
qDebug()<<"read all:"<<reply_data;
QJsonParseError json_error;
QJsonDocument document = QJsonDocument::fromJson(reply_data,&json_error);
if(json_error.error==QJsonParseError::NoError)
{
if(document.isObject())
{
const QJsonObject obj = document.object();
qDebug()<<"obj:"<<obj;
if(obj.contains("Accept-Language"))
{
QJsonValue value = obj.value("Accept-Language");
qDebug()<<"value"<<value;
}
}
}
else
qDebug()<<"json error:"<<json_error.errorString();
}
reply->deleteLater();
}
http组成
一条http请求基本上分为Url,Header,Body三部分
创建QNetworkRequest
QNetworkRequest request;
request.setUrl(QUrl(url));
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
request.setRawHeader("Content_Type","application/json");
关于Content_Type
Content_Type,意为数据格式标签,种类有很多,常见的有以下几种:
类型 | 字符串 |
---|
html文档标记 | text/html | 普通ASCII文档标记 | text/html | JPEG图片标记 | image/jpeg | GIF图片标记 | image/gif | js文档标记 | application/javascript | xml文件标记 | application/xml |
最常用的是:application/x-www-form-urlencoded 和 application/json 两者设置Body参数的方法是不一样的。 前者:
QByteArray body;body.append("option=pencil&");
body.append("image=");
body.append(QUrl::toPercentEncoding(Picbase64));
manager->post(request,body);
后者:
QJsonObject postjson;
postjson.insert("image",str_base64);
postjson.insert("option",m_style);
QJsonDocument doc;
doc.setObject(postjson);
QByteArray postdata = doc.toJson(QJsonDocument::Compact);
manager->post(request,postdata);
实例
利用百度翻译API编写翻译器
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonValue>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QUrl>
#include <QUrlQuery>
#include <QSettings>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void replyFinished(QNetworkReply *reply);
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
void on_pushButton_4_clicked();
void on_btn_mode_clicked();
void on_btn_go_clicked();
void on_cb_from_currentIndexChanged(const QString &arg1);
void on_cb_to_currentIndexChanged(const QString &arg1);
private:
Ui::Widget *ui;
QNetworkAccessManager *manager;
bool mode=true;
QString from;
QString to;
void translate(QString lang_src,QString lang_dst);
};
#endif
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include "stdlib.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
manager = new QNetworkAccessManager(this);
connect(manager,&QNetworkAccessManager::finished,this,&Widget::replyFinished);
this->setWindowFlags(Qt::WindowStaysOnTopHint);
this->setWindowTitle("翻译器-mja V3.0");
ui->wid_pro->setVisible(false);
QSettings setini("set.ini");
ui->cb_from->setCurrentIndex(setini.value("set/from",0).toInt());
ui->cb_to->setCurrentIndex(setini.value("set/to",0).toInt());
from=setini.value("set/lang_src","zh").toString();
to=setini.value("set/lang_dst","zh").toString();
setini.deleteLater();
}
Widget::~Widget()
{
delete ui;
}
void Widget::replyFinished(QNetworkReply *reply)
{
if(reply->error()==QNetworkReply::NoError)
{
QByteArray ba = reply->readAll();
QJsonDocument doc = QJsonDocument::fromJson(ba);
QJsonObject obj = doc.object();
qDebug()<<obj;
QJsonArray qa = obj.value("trans_result").toArray();
QJsonValue qv = qa.takeAt(0);
QJsonObject obj2 = qv.toObject();
QString res = obj2.value("dst").toString();
ui->textEdit->append(res);
}
}
void Widget::on_pushButton_clicked()
{
translate("zh","en");
}
void Widget::on_pushButton_2_clicked()
{
translate("en","zh");
}
void Widget::translate(QString lang_src, QString lang_dst)
{
ui->textEdit->clear();
QNetworkRequest request;
QUrl url("http://fanyi-api.baidu.com/api/trans/vip/translate");
int a = rand();
QString str1="********"+ui->lineEdit->text()+QString::number(a)+"***********";
QByteArray ba = QCryptographicHash::hash(str1.toUtf8(),QCryptographicHash::Md5);
QString str2=ba.toHex();
QUrlQuery qry;
qry.addQueryItem("q",ui->lineEdit->text());
qry.addQueryItem("from",lang_src);
qry.addQueryItem("to",lang_dst);
qry.addQueryItem("appid","20211207001021383");
qry.addQueryItem("salt",QString::number(a));
qry.addQueryItem("sign",str2);
qry.addQueryItem("dict","0");
url.setQuery(qry);
request.setUrl(url);
manager->get(request);
}
void Widget::on_pushButton_3_clicked()
{
translate("zh","jp");
}
void Widget::on_pushButton_4_clicked()
{
translate("jp","zh");
}
void Widget::on_btn_mode_clicked()
{
if(mode)
{
mode=false;
ui->wid_simple->setVisible(false);
ui->wid_pro->setVisible(true);
ui->btn_mode->setText("普");
}
else
{
mode=true;
ui->wid_simple->setVisible(true);
ui->wid_pro->setVisible(false);
ui->btn_mode->setText("简");
}
}
void Widget::on_btn_go_clicked()
{
translate(from,to);
}
void Widget::on_cb_from_currentIndexChanged(const QString &arg1)
{
from=arg1.mid(arg1.indexOf("-")+1,arg1.length());
QSettings setini("set.ini");
setini.setValue("set/from",ui->cb_from->currentIndex());
setini.deleteLater();
}
void Widget::on_cb_to_currentIndexChanged(const QString &arg1)
{
to=arg1.mid(arg1.indexOf("-")+1,arg1.length());
QSettings setini("set.ini");
setini.setValue("set/to",ui->cb_to->currentIndex());
setini.deleteLater();
}
|