<span style="font-size:18px;">#include "accessweather.h"
#include <QDebug>
#include <QEventLoop>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <boost/config.hpp>
AccessWeather::AccessWeather(QObject *parent)
: QObject(parent)
{
m_accessWeather = new QNetworkAccessManager(this);
connect(m_accessWeather,
SIGNAL(finished ( QNetworkReply * )),
this,
SLOT(slotFinished ( QNetworkReply * ))
);
}
AccessWeather::~AccessWeather()
{
}
QString AccessWeather::getWeather( const QString& city )
{
QNetworkRequest req;
populateRequest(city, &req);
m_accessWeather->get(req);
//wait for get weather
QEventLoop loop;
connect(m_accessWeather, SIGNAL(finished ( QNetworkReply * )), &loop, SLOT(quit()));
return QString();
}
void AccessWeather::slotFinished( QNetworkReply * reply)
{
QNetworkReply::NetworkError err = reply->error();
if(QNetworkReply::NoError != err)
return;
QUrl newUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
if (!newUrl.isEmpty())
{
//读取新的地址
m_accessWeather->get(QNetworkRequest(newUrl));
}
else
{
QByteArray ba = reply->readAll();
qDebug()<<ba;
}
int bp = 0;
}
void AccessWeather::populateRequest( const QString& city, QNetworkRequest* req )
{
QString percentEncode = city.toLocal8Bit().toPercentEncoding();
QString strReqestLine = QString("http://www.tianqi.com/index.php?c=tianqi&a=search&city=%1").arg(percentEncode);
<strong><span style="color:#ff6666;">//如果不使用这个,则会导致url.encodedQuery()重新的错误解析而导致错误(编码格式问题)</span></strong>
QUrl url = QUrl::fromEncoded(strReqestLine.toAscii());
QString rurl = url.encodedPath();
QString rurl2 = url.encodedQuery();
req->setUrl(url);
<strong><em><u><span style="color:#cc0000;">//req->setRawHeader("Host", "http://www.tianqi.com/");//不需要设置Host,默认会有,否则会导致错误的信息提交而获取不到正确信息</span></u></em>
<em><span style="color:#ff0000;">//下列信息可有可无,如果没有则会有默认的值
req->setRawHeader("Connection", "keep-alive");
req->setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
req->setRawHeader("Referer", "http://www.tianqi.com/");
req->setRawHeader("Accept-Encoding", "gzip,deflate,sdch");
req->setRawHeader("Accept-Language", "zh-CN,zh;q=0.8");
req->setRawHeader("Cookie", "cityPy=baoding; AJSTAT_ok_pages=1; AJSTAT_ok_times=1; bdshare_firstime=1412864742830");
req->setRawHeader("Content-Type", "text/html; charset=GBK");</span></em></strong>
//GET /index.php?c=tianqi&a=search&city=%E7%9F%B3%E5%AE%B6%E5%BA%84 HTTP/1.1\r\n //直接使用中文'石家庄'而导致的错误
//不使用QUrl::fromEncoded而导致的错误,会将%重新解析为%25
//GET /index.php?c=tianqi&a=search&city=%25%CA%25%AF%25%BC%25%D2%25%D7%25%AF HTTP/1.1\r\n
//正确的提交结果
//GET /index.php?c=tianqi&a=search&city=%CA%AF%BC%D2%D7%AF HTTP/1.1\r\n
}
</span>
QNetworkAccessManger的用法