实用QT5访问HTTP/以及HTTPS协议访问
并且调用Json解析
#include "mywidget.h"
#include "ui_mywidget.h"
#include
#include
#include
#include
#include
#include
#include
#include
MyWidget::MyWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::MyWidget)
{
ui->setupUi(this);
QUrl url;
m_AccessManager = new QNetworkAccessManager(this);
url.setUrl("http://ip.taobao.com/service/getIpInfo2.php");
QSslConfiguration config;
config.setPeerVerifyMode(QSslSocket::VerifyNone);
config.setProtocol(QSsl::TlsV1SslV3);
m_Request.setSslConfiguration(config);
m_Request.setUrl(url);
QByteArray sendData;
sendData = QString::fromStdString("ip=27.106.204.0").toLocal8Bit();
m_Request.setRawHeader("Accept","*/*");
m_Request.setRawHeader("Accept-Language","zh-CN,zh;q=0.9");
m_Request.setRawHeader("Content-Type","application/x-www-form-urlencoded");
m_Request.setRawHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
m_Request.setRawHeader("X-Requested-With:","XMLHttpRequest");
m_Request.setRawHeader("Referer","http://ip.taobao.com/ipSearch.html");
m_Reply = m_AccessManager->post(m_Request,sendData);
connect(m\_AccessManager,&QNetworkAccessManager::finished,this,&MyWidget::ReplyReadFunc);
}
MyWidget::~MyWidget()
{
delete ui;
}
void MyWidget::ReplyReadFunc(QNetworkReply* Reply)
{
int NetworkErrors = -;
NetworkErrors = Reply->error();
QString ip;
QString country;
QString region;
QString isp;
if(NetworkErrors ==QNetworkReply::NoError)
{
QByteArray databuff = Reply->readAll();
QString result = QString::fromStdString(databuff.toStdString()).toUtf8();
QJsonDocument document;
QJsonParseError ParseError;
document =QJsonDocument::fromJson(result.toUtf8(),&ParseError);
if(!document.isNull() && ParseError.error == QJsonParseError::NoError)
{
if(document.isObject())
{
QJsonObject Object = document.object(); //获取文档对象
if(!Object.isEmpty())
{
if(Object.contains("data")) //先判断有没有
{
QJsonValue dataObj = Object.value("data");
if(dataObj.isObject()) //判断是否是对象
{
QJsonObject ObjectData = dataObj.toObject();
if(ObjectData.contains("ip"))
{
QJsonValue ipVal = ObjectData.value("ip");
if(ipVal.isString())
{
ip = ipVal.toString();
}
}
if(ObjectData.contains("region"))
{
QJsonValue regionVal = ObjectData.value("region");
if(regionVal.isString())
{
region = regionVal.toString();
}
}
if(ObjectData.contains("isp"))
{
QJsonValue ispVal = ObjectData.value("isp");
if(ispVal.isString())
{
isp = ispVal.toString();
}
}
}
}
}
}
country+="您的ip:"+ip;
country+="所在城市:"+region;
country+="运营商:"+isp;
qDebug()<<country.toStdString().c\_str();
}
}
}
运行结果
手机扫一扫
移动阅读更方便
你可能感兴趣的文章