ExternalIP.cpp Example File
httptest/src/ExternalIP.cpp
#include "ExternalIP.hpp"
#include "AppSettings.hpp"
#include <bb/data/JsonDataAccess>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QSettings>
#include <QSslConfiguration>
#include <QUrl>
ExternalIP::ExternalIP(QObject* parent)
: QObject(parent)
, m_networkAccessManager(new QNetworkAccessManager(this))
{
}
void ExternalIP::getIP()
{
const QUrl url("http://httpbin.org/ip");
QNetworkRequest request(url);
if (AppSettings::isUsingHttps()) {
request.setUrl(QUrl("https://httpbin.org/ip"));
QSslConfiguration config = request.sslConfiguration();
config.setPeerVerifyMode(QSslSocket::VerifyNone);
config.setProtocol(QSsl::TlsV1);
request.setSslConfiguration(config);
}
QNetworkReply* reply = m_networkAccessManager->get(request);
bool ok = connect(reply, SIGNAL(finished()), this, SLOT(onGetReply()));
Q_ASSERT(ok);
Q_UNUSED(ok);
}
void ExternalIP::onGetReply()
{
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
QString response;
if (reply) {
if (reply->error() == QNetworkReply::NoError) {
const int available = reply->bytesAvailable();
if (available > 0) {
const QByteArray buffer(reply->readAll());
bb::data::JsonDataAccess ja;
const QVariant jsonva = ja.loadFromBuffer(buffer);
const QMap<QString, QVariant> externalip = jsonva.toMap();
foreach (const QVariant &value, externalip) {
response += value.toString();
}
}
} else {
const int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
response = tr("Http Error: %1").arg(httpStatus);
}
reply->deleteLater();
}
if (response.trimmed().isEmpty()) {
response = tr("Unable to retrieve ip address");
}
emit complete(response);
}