11人参与 • 2025-03-03 • C/C++
一定要记得在.pro文件里面添加network
模块
包含一些必要的头文件
#include "mainwindow.h" #include "ui_mainwindow.h" #include <qnetworkaccessmanager> #include <qnetworkrequest> #include <qnetworkreply> #include <qdebug>
用qnetworkaccessmanager创建一个网络访问管理器对象manager,和连接网络网络完成时的信号与槽
qnetworkaccessmanager *manager = new qnetworkaccessmanager(this); //创建一个网络访问管理器,处理http请求
connect(manager,&qnetworkaccessmanager::finished,[](){ qdebug() << "manager finish"; }); //连接网络请求完成时的lambda表达式
用qurl创建一个接口
qurl urlweather("http://gfeljm.tianqiapi.com/api?unescape=1&version=v9&appid=63688735&appsecret=g9bigc28"); //创建url
用qnetworkrequest创建网络请求对象,设置接口
qnetworkrequest res(urlweather); //创建网络请求对象,设置url
用qnetworkreply创建一个回复对象,接收get请求,并连接请求完成时的信号与槽
reply = manager->get(res); //发送get请求 connect(reply,&qnetworkreply::finished,this,&mainwindow::httpreply); //连接请求完成时的信号和槽函数
自定义一个槽函数来回应请求完成时的处理
void mainwindow::httpreply() { // int rescode = qbytearray dataweather = reply->readall(); //读取返回的数据 qdebug() << qstring::fromutf8(dataweather) ; //以utf8格式打印数据 }
connect(reply,&qnetworkreply::finished,this,&mainwindow::httpreply); //连接请求完成时的信号和槽函数
#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
#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请求内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论