wordpress用网站测速,wordpress登陆页文件夹,南海做网站公司,崇文手机网站建设前言#xff1a;
在写一个天气预报模块时#xff0c;需要一个定位功能#xff0c;在网上翻来翻去才找着#xff0c;放在这里留着回顾下#xff0c;也帮下有需要的人
正文#xff1a; 一开始我想着直接调用百度地图的API来定位#xff0c; 然后我就想先获取本机IP的方…前言
在写一个天气预报模块时需要一个定位功能在网上翻来翻去才找着放在这里留着回顾下也帮下有需要的人
正文 一开始我想着直接调用百度地图的API来定位 然后我就想先获取本机IP的方式然后调用百度地图的api来进行对位结果怎么弄都只能获取到私有IP私有IP是没法用来定位但还是具体代码还是贴在这下
QString MainWindow::getIP()//返回一个IP地址但是是私有的
{QListQHostAddress listQNetworkInterface::allAddresses();foreach (QHostAddress address, list) {if(address.protocol()QAbstractSocket::IPv4Protocol)return address.toString();}return 0.0.0.0;
}重点来了我找到了一个可以获取公有IP和当前用户所在市的API,http://whois.pconline.com.cn/ipJson.jsp?jsontrue,调用这个API就可以了
要调用之前要写一个类去存放(拆解)返回JSON数组很简单毕竟这个JSON数组的内容很少
#include QObject.h
class location{
public:location(){ip;pro;proCode;city;cityCode0;}QString ip;QString pro;QString proCode;QString city;QString cityCode;
};
http请求 在头文件定义两个变量,还有需要用的到函数
protected://解析本机外网IP,并获取所在市void locationInfo();
private slots://处理定位API请求void onLocationInfoReceived(QNetworkReply *reply);private://定位数据location mlocation;//定位用的API的请求QNetworkAccessManager* mLocationManger;放在在构造函数 //定位请求mLocationMangernew QNetworkAccessManager(this);
connect(mLocationManger,QNetworkAccessManager::finished,this,MainWindow::onLocationInfoReceived);locationInfo();void MainWindow::locationInfo()
{QUrl url(http://whois.pconline.com.cn/ipJson.jsp?jsontrue);mLocationManger-get(QNetworkRequest(url));
}
void MainWindow::onLocationInfoReceived(QNetworkReply *reply)
{if (reply-error() QNetworkReply::NoError) {QString data QString::fromLocal8Bit(reply-readAll());QJsonDocument jsonDocument QJsonDocument::fromJson(data.toUtf8());QJsonObject jsonObject jsonDocument.object();qDebug()read all:jsonObject;mlocation.ip jsonObject.value(ip).toString();mlocation.pro jsonObject.value(pro).toString();mlocation.proCode jsonObject.value(proCode).toString();mlocation.city jsonObject.value(city).toString();mlocation.cityCode jsonObject.value(cityCode).toString();} else {qDebug() Location request error: reply-errorString();}qDebug()mlocation.city;//请求天气信息getWeatherInfo(mlocation.city);reply-deleteLater();//deleteLater 是 Qt 框架中的一个方法用于在对象的生命周期结束时安全地删除对象
}