引入網(wǎng)絡模塊:
QT += core gui network
mainwindow.h:文章來源:http://www.zghlxwxcb.cn/news/detail-647000.html
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMessageBox>
#include <QNetworkAccessManager>
#include <QNetworkReply>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
// 請求天氣數(shù)據(jù)成功后自動調用 onReply() 槽函數(shù)
void onReply(QNetworkReply* reply);
protected:
// 根據(jù)城市編碼獲取城市天氣信息
void getWeatherInfo(QString cityCode);
private:
Ui::MainWindow *ui;
// 發(fā)送網(wǎng)絡請求 和 處理網(wǎng)絡響應
QNetworkAccessManager *m_networkAccessManager;
};
#endif // MAINWINDOW_H
mainwindow.cpp:文章來源地址http://www.zghlxwxcb.cn/news/detail-647000.html
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_networkAccessManager = new QNetworkAccessManager(this);
// 獲取天氣數(shù)據(jù)完成后自動觸發(fā)系統(tǒng)信號 finished,調用自定義槽函數(shù) onReply
connect(m_networkAccessManager,&QNetworkAccessManager::finished,this,&MainWindow::onReply);
// 根據(jù)城市編碼獲取城市天氣信息
// 101010100為北京市天氣編碼
getWeatherInfo("101010100");
}
MainWindow::~MainWindow()
{
delete ui;
}
// 請求數(shù)據(jù)成功后自動調用 onReply() 槽函數(shù)
void MainWindow::onReply(QNetworkReply *reply)
{
// 狀態(tài)碼:響應成功為 200
int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
// qDebug()<<"請求方式:"<<reply->operation();
// qDebug()<<"狀態(tài)碼:"<<statusCode;
// qDebug()<<"URL:"<<reply->url();
// qDebug()<<"響應頭:"<<reply->rawHeaderList();
if(reply->error() != QNetworkReply::NoError || statusCode != 200)
{// 天氣數(shù)據(jù)請求失敗
QMessageBox::warning(this,"天氣","天氣數(shù)據(jù)請求失敗",QMessageBox::Ok);
}
else
{// 天氣數(shù)據(jù)請求成功
QByteArray byteArray = reply->readAll();
qDebug()<<" info::::::"<<byteArray.data();
}
// 必須釋放內存,否則會造成內存泄露
reply->deleteLater();
}
// 根據(jù)城市編碼獲取城市天氣信息
void MainWindow::getWeatherInfo(QString cityCode)
{
QUrl url("http://t.weather.itboy.net/api/weather/city/"+cityCode);
// 使用 get 請求方式
m_networkAccessManager->get(QNetworkRequest(url));
}
到了這里,關于Qt 使用HTTP請求網(wǎng)絡API并接收返回的JSON格式的數(shù)據(jù)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!