Qt QNetworkReply connection closed - c++

I try to execute post method in c++ to a url https://..., but I receive connection closed error.
I see that my code works if I use another url like https://www.google.gr.
If I remove the port 8181 I get error: server replied:not found.
My code is
static const char *REQUEST_URL="https://...";
static const char *USER = "....";
static const char *PASSWORD = "....";
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
finishedexecuted=0;
QByteArray postData;
postData.append("username=...");
postData.append("password= ...");
m_network = new QNetworkAccessManager(this);
QNetworkRequest request;
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QUrl url=QUrl(REQUEST_URL);
request.setUrl(url);
QSslConfiguration config = request.sslConfiguration();
QList<QSslCertificate> certs =
QSslCertificate::fromPath("pistopoiitiko.crt");
config.setCaCertificates(certs);
request.setSslConfiguration(config);
QNetworkReply *reply = m_network->post(request,postData);
downloadTime.start();
QObject::connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
SLOT(slotSetProgress(qint64,qint64)));
QObject::connect(m_network, SIGNAL(finished(QNetworkReply *)),
SLOT(slotRequestFinished(QNetworkReply *)));
connect(m_network,
SIGNAL(sslErrors(QNetworkReply *, const QList<QSslError> &)),
this,
SLOT(sslError(QNetworkReply*, const QList<QSslError> &)));
}
void MainWindow::sslError(QNetworkReply* reply,
const QList<QSslError> &errors )
{...}
void MainWindow::slotRequestFinished(QNetworkReply *reply)
{
...
if (reply->error() > 0) {
m_label->setText("Error number = " + reply->errorString());
}
...
}
void MainWindow::slotSetProgress(qint64 received, qint64 total)
{...}
Any ideas?

i achieved to overcome this problem with this code
QSslConfiguration config = QSslConfiguration::defaultConfiguration();
config.setProtocol(QSsl::SslV3);
then i received ssl errors that i passed with ignoresslerrors()

Related

Download a file using http client from ftp server

I have an existing C++/Qt source code for the firmware update. HTTP client used to download the file.
This piece of code works fine if I'll provide http://<path to file>
But http client failed to download from ftp://<path to down load>. It shows downloaded file size zero with ftp.
As per StackOverflow, It should work for for both. I try to use setScheme("ftp") and other small changes. But does not work.
void HttpClient::onDownloadProgress(qint64 bytesReceived,
qint64 bytesTotal)
{
emit downloadUpdateProgress(
static_cast<int>((bytesReceived * 1.0f / bytesTotal * 1.0f) * 100));
}
void HttpClient::onReadyRead()
{
auto reply = qobject_cast<QNetworkReply *>(QObject::sender());
if (reply) {
QNetworkRequest request(reply->request());
auto device = qobject_cast<QIODevice *>(request.originatingObject());
if (device) {
device->write(reply->readAll());
}
}
}
bool HttpClient::post(const QUrl &url, const QByteArray &data,
QIODevice *device)
{
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader,
"application/x-www-form-urlencoded");
request.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
QNetworkRequest::AlwaysNetwork);
request.setSslConfiguration(getSslConfig());
request.setOriginatingObject(device);
QNetworkReply *reply = _networkAccessManager->post(request, data);
connect(reply, &QNetworkReply::readyRead, this, &HttpClientImpl::onReadyRead);
bool result = waitForFinished(reply, 30 * 1000);
return result;
}
bool HttpClientImpl::get(const QUrl &url, QIODevice *device)
{
QNetworkRequest request(url);
request.setSslConfiguration(getSslConfig());
request.setOriginatingObject(device);
QNetworkReply *reply = _networkAccessManager->get(request);
connect(reply, &QNetworkReply::downloadProgress, this,
&HttpClientImpl::onDownloadProgress);
connect(reply, &QNetworkReply::readyRead, this, &HttpClientImpl::onReadyRead);
bool result = waitForFinished(reply);
return result;
}
It should download the correct file size.

Getting empty response in HTTP get request in QT QNetworkAccessManager

I am doing a simple HTTP get request to www.google.co.in but I am getting empty string in response.
Here is my code:
void MainWindow::on_pushButton_clicked()
{
QNetworkAccessManager * mgr = new QNetworkAccessManager(this);
connect(mgr,SIGNAL(finished(QNetworkReply*)),this,SLOT(onfinish(QNetworkReply*)));
QUrl url("www.google.co.in");
url.setScheme("http");
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
mgr->get(QNetworkRequest(QUrl("www.google.co.in")));
}
void MainWindow::onfinish(QNetworkReply *rep)
{
QByteArray bts = rep->readAll();
QString str(bts);
qDebug() << str;
}
Output is :""
Facing same issue when doing post request to my own server.
In pro file I have done QT += core gui network
You have to add the correct URL, in addition it is recommended that you use the new connection between signals and slots, and finally you must remove the QNetworkReply:
void MainWindow::on_pushButton_clicked()
{
QUrl url("https://www.google.co.in/");
QNetworkAccessManager *mgr = new QNetworkAccessManager(this);
connect(mgr,&QNetworkAccessManager::finished,this,&MainWindow::onfinish);
mgr->get(QNetworkRequest(url));
}
void MainWindow::onfinish(QNetworkReply *rep)
{
QByteArray bts = rep->readAll();
QString str(bts);
qDebug() << str;
rep->deleteLater();
}

QNetworkAccessManager never emits finished() signal

I'm working on a module for a project where HTTP GET requests are used to retrieve some XML data, which is then converted to another format and send to a sub-system.
The code I have written so far is below:
CMakeLists.txt:
project(HttpDemo)
cmake_minimum_required(VERSION 2.8)
set(CMAKE_BUILD_TYPE Debug)
#find_package(Qt5Widgets)
find_package(Qt5Core)
find_package(Qt5Network)
set(CMAKE_AUTOMOC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
aux_source_directory(. SRC_LIST)
add_executable(${PROJECT_NAME} ${SRC_LIST})
qt5_use_modules(${PROJECT_NAME} Core Network) #Gui Widgets
main.cpp
#include <QtCore>
#include <QtNetwork>
class HttpHandler : public QObject
{
Q_OBJECT
public:
HttpHandler(QObject* parent=Q_NULLPTR) : QObject(parent)
{
QObject::connect(&nm, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
qDebug() << QSslSocket::sslLibraryBuildVersionString();
}
private:
QNetworkAccessManager nm;
public slots:
void post(QString urlLink)
{
QUrl url(urlLink);
QNetworkRequest request(url);
QSslConfiguration sslConf;
sslConf.setProtocol(QSsl::SslV3);
request.setSslConfiguration(sslConf);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencded");
QUrlQuery query;
query.addQueryItem("client_id", "1234");
query.addQueryItem("code", "abcd");
QUrl params;
params.setQuery(query);
nm.post(request, params.toEncoded());
}
void get(QString urlLink)
{
QUrl url(urlLink);
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
nm.get(request);
}
void replyFinished(QNetworkReply* reply)
{
QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
if(statusCode.isValid())
{
// Print or catch the status code
QString status = statusCode.toString(); // or status_code.toInt();
qDebug() << status;
qDebug() << QString::fromStdString(reply->readAll().toStdString());
}
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
HttpHandler hh;
hh.get("SOME_URL");
return a.exec();
}
#include "main.moc"
With SOME_URL I have tried a lot of links all of which work without any issues in let's say the Http Requester addon for Firefox. I get:
"OpenSSL 1.0.1j 15 Oct 2014"
qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method
qt.network.ssl: QSslSocket: cannot resolve SSLv2_server_method
According to the authority called the Internet this shouldn't be a problem. One thing's for certain - my replyFinished(QNetworkReply*) slot doesn't get triggered although it is connected to the finished() signal of the QNetworkAccessManager. This means that whatever the reason the signal is not emitted. Changing the QSslConfiguration to a different QSsl::SslProtocol doesn't make a difference in the outcome.
UPDATE (as requested in the comments):
Following code uses readyRead() and dynamically allocated reply. The result - same as above.
#include <QtCore>
#include <QtNetwork>
class HttpHandler : public QObject
{
Q_OBJECT
public:
HttpHandler(QObject* parent=Q_NULLPTR) : QObject(parent)
{
qDebug() << QSslSocket::sslLibraryBuildVersionString();
this->manager = new QNetworkAccessManager(this);
this->reply = Q_NULLPTR;
}
private:
QNetworkAccessManager* manager;
QNetworkReply* reply;
signals:
void finished();
public slots:
void post(QString urlLink)
{
QUrl url(urlLink);
QNetworkRequest request(url);
QSslConfiguration sslConf;
sslConf.setProtocol(QSsl::SslV2);
request.setSslConfiguration(sslConf);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QUrlQuery query;
query.addQueryItem("client_id", "1234");
query.addQueryItem("code", "abcd");
QUrl params;
params.setQuery(query);
manager->post(request, params.toEncoded());
}
void get(QString urlLink)
{
QUrl url(urlLink);
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
this->reply = manager->get(request);
QObject::connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
}
void slotReadyRead()
{
qDebug() << "Hello"; // I never land here
}
void replyFinished(QNetworkReply* reply)
{
QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
if(statusCode.isValid())
{
QString status = statusCode.toString(); // or status_code.toInt();
qDebug() << status;
qDebug() << QString::fromStdString(reply->readAll().toStdString());
}
emit finished();
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
HttpHandler *hh = new HttpHandler(&a);
QObject::connect(hh, SIGNAL(finished()), &a, SLOT(quit()));
hh->get("http://httpbin.org/ip"); // or any other httpbin.org endpoint
return a.exec();
}
#include "main.moc"
UPDATE 2:
I just found an example in the Qt documentation. Downloaded, compiled and ran the thing - same error but it works.
Issue resolved (see here). Basically the problem was the company's proxy. A colleague of mine gave it a shot and replaced the HTTP with HTTPS (even though the link is HTTP) and it worked all of a sudden. Then it struck us - the company's proxy caches HTTP (and does other things too), which leads to huge delays and if the timeout tolerance is small enough QNetworkAccessManager will return a socket timeout.
Using QNetworkProxyFactory::setUseSystemConfiguration(true) enables the proxy in a way that doesn't make your application dependent on a configuration in your code but rather the configuration of the system.

QNetworkAccessManager does not emit signal

So I have this code:
QUrl url("http://...");
QNetworkRequest request(url);
QNetworkReply *reply = m_networkManager->get(request);
connect(reply, SIGNAL(finished()), SLOT(onRequestCompleted()));
connect(reply,SIGNAL(error(QNetworkReply::NetworkError)),SLOT(onError(QNetworkReply::NetworkError)));
and I cant get signal to the other fuction
void IpResolver::onRequestCompleted()
{
QString webContent;
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
if (reply)
{
if (reply->error() == QNetworkReply::NoError)
{
QString webContent = reply->readAll();
}
}
}
I cant figure out the solution, help please.
I don't know what exactly you want, but:
Why do you use reply pointer instead of some kind onRequestCompleted(QNetworkReply *reply)?
If you do so:
QUrl url("http://...");
QNetworkRequest request(url);
connect(m_networkManager, &QNetworkAccessManager::finished, this, &IpResolver::onRequestCompleted);
m_networkManager->get(request);
And your slot will be, for example:
void IpResolver::onRequestCompleted(QNetworkReply *reply)
{
QString webContent;
if (reply->error() == QNetworkReply::NoError)
webContent = reply->readAll();
}

create a http communication on blackberry 10 cascade

I'm newbie on development blackberry 10 cascades. I need to use httpget to connect on file xml and get dat from it to display it on list.
There is an example can help me to make http communication or a tutoriel?
All the links for http communication like this https://developer.blackberry.com/cascades/documentation/device_platform/networking/tutorial_http_comm.html didn't work I get 404
Use QNetworkAccessManager, QNetworkRequest and QNetworkReply classes to make http connection.
QNetworkAccessManager* netManager = new QNetworkAccessManager();
QUrl myurl(yourURL);
QNetworkRequest req(url);
QNetworkReply* ipReply = netManager->get(req);
connect(ipReply, SIGNAL(finished(QNetworkReply*)), this, SLOT(onReply(QNetworkReply*)));
}
In onReply slot parse your response
if (reply) {
if (reply->error() == QNetworkReply::NoError) {
int available = reply->bytesAvailable();
if (available > 0) {
int bufSize = sizeof(char) * available + sizeof(char);
QByteArray buffer(bufSize, 0);
int read = reply->read(buffer.data(), available);
response = QString(buffer);
}
} else {
response =
QString("Error: ") + reply->errorString()
+ QString(" status:")
+ reply->attribute(
QNetworkRequest::HttpStatusCodeAttribute).toString();
}
reply->deleteLater();
}
Visit this page for more information
use this code...
QNetworkAccessManager* netManager = new QNetworkAccessManager();
QUrl myurl("http://******");
QNetworkRequest req(myurl);
QNetworkReply* ipReply = netManager->get(req);
QEventLoop eventLoop;
QObject::connect(ipReply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
eventLoop.exec();
std::cout << "finished" << std::endl; //request finished here
requestFinished(ipReply);