1、添加network模块
一定要记得在.pro文件里面添加network模块

2、包含改头文件
包含一些必要的头文件
#include "mainwindow.h" #include "ui_mainwindow.h" #include <qnetworkaccessmanager> #include <qnetworkrequest> #include <qnetworkreply> #include <qdebug>
3、创建网络访问管理器
用qnetworkaccessmanager创建一个网络访问管理器对象manager,和连接网络网络完成时的信号与槽
qnetworkaccessmanager *manager = new qnetworkaccessmanager(this); //创建一个网络访问管理器,处理http请求
connect(manager,&qnetworkaccessmanager::finished,[](){
qdebug() << "manager finish";
}); //连接网络请求完成时的lambda表达式
4、创建接口
用qurl创建一个接口
qurl urlweather("http://gfeljm.tianqiapi.com/api?unescape=1&version=v9&appid=63688735&appsecret=g9bigc28"); //创建url5、创建网络请求对象
用qnetworkrequest创建网络请求对象,设置接口
qnetworkrequest res(urlweather); //创建网络请求对象,设置url
6、创建一个回复对象,接收get请求
用qnetworkreply创建一个回复对象,接收get请求,并连接请求完成时的信号与槽

reply = manager->get(res); //发送get请求 connect(reply,&qnetworkreply::finished,this,&mainwindow::httpreply); //连接请求完成时的信号和槽函数
7、自定义槽函数
自定义一个槽函数来回应请求完成时的处理

void mainwindow::httpreply()
{
// int rescode =
qbytearray dataweather = reply->readall(); //读取返回的数据
qdebug() << qstring::fromutf8(dataweather) ; //以utf8格式打印数据
}
connect(reply,&qnetworkreply::finished,this,&mainwindow::httpreply); //连接请求完成时的信号和槽函数
8、.h文件
#ifndef mainwindow_h
#define mainwindow_h
#include <qnetworkreply>
#include <qmainwindow>
qt_begin_namespace
namespace ui { class mainwindow; }
qt_end_namespace
class mainwindow : public qmainwindow
{
q_object
public:
mainwindow(qwidget *parent = nullptr);
~mainwindow();
private slots:
void httpreply();
private:
ui::mainwindow *ui;
qnetworkreply* reply;
};
#endif // mainwindow_h
9、.cpp文件
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <qnetworkaccessmanager>
#include <qnetworkrequest>
#include <qnetworkreply>
#include <qdebug>
mainwindow::mainwindow(qwidget *parent)
: qmainwindow(parent)
, ui(new ui::mainwindow)
{
ui->setupui(this);
qnetworkaccessmanager *manager = new qnetworkaccessmanager(this); //创建一个网络访问管理器,处理http请求
connect(manager,&qnetworkaccessmanager::finished,[](){
qdebug() << "manager finish";
}); //连接网络请求完成时的lambda表达式
// qstring weatherurl = "http://gfeljm.tianqiapi.com/api?unescape=1&version=v9&appid=63688735&appsecret=g9bigc28";
// qurl urlweather(weatherurl); //创建url
qurl urlweather("http://gfeljm.tianqiapi.com/api?unescape=1&version=v9&appid=63688735&appsecret=g9bigc28"); //创建url
qnetworkrequest res(urlweather); //创建网络请求对象,设置url
reply = manager->get(res); //发送get请求
connect(reply,&qnetworkreply::finished,this,&mainwindow::httpreply); //连接请求完成时的信号和槽函数
}
mainwindow::~mainwindow()
{
delete ui;
}
void mainwindow::httpreply()
{
// int rescode =
qbytearray dataweather = reply->readall(); //读取返回的数据
qdebug() << qstring::fromutf8(dataweather) ; //以utf8格式打印数据
}
到此这篇关于qt实现发送http请求的示例详解的文章就介绍到这了,更多相关qt发送http请求内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论