Qt How sent post HTTPS with SSL - c++

Qt How send simple post HTTPS with SSL ?
The program is supposed to send posts via HTTPS using QNetworkAccessManager.
Below is a simple example of my code.
QUrlQuery params;
QByteArray dane;
params.addQueryItem("mWyslijpost", ui->lineEdit->text());
dane.append(params.toString());
QUrl url("https://81.2.244.83/Testpostssl/infotest.php");
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
QNetworkReply *reply = manager->post(request, dane);
QFile certFile(":/crt/cert.crt");
Q_ASSERT(certFile.open(QIODevice::ReadOnly));
QSslCertificate cert(&certFile, QSsl::Pem);
QSslSocket * sslSocket = new QSslSocket(this);
sslSocket->addCaCertificate(cert);
sslSocket->connectToHostEncrypted(SERVER, 443);
if (!sslSocket->waitForEncrypted())
{
qDebug() << "Info " << sslSocket->errorString();
return false;
}
QSslConfiguration config = sslSocket->sslConfiguration();
config.setProtocol(QSsl::TlsV1_2);
sslSocket->setSslConfiguration(config);
reply->setSslConfiguration(config);
// wait
QEventLoop elCzekaj;
connect(reply, SIGNAL(finished()), &elCzekaj, SLOT(quit()));
elCzekaj.exec();
if(reply->error() == QNetworkReply::NoError)
{
qDebug() << reply->readAll();
}
else
{
qDebug() << "Error...";
qDebug() << reply->errorString();
}
How to download certificates from server ?
How to configure QSsl ?

To get the cert from the peer try something like this:
QSslSocket *socket = new QSslSocket();
QObject::connect(socket,
&QSslSocket::encrypted,
[=](){qDebug() << socket->peerCertificate() << " cert";}
);
socket->connectToHostEncrypted("stackoverflow.com", 443);
Regarding the question: "How to configure QSsl", that depends on what you want to do. If you simply want to fetch something from a Webserver over TLS, just use the QNetworkAccessManager. The defaults there will do.

Related

QNetworkReply - Strange error in enum, OperationCanceled instead of Timeout?

My API server is turned off and i run following code.
I dont understand why QNetworkReply::OperationCanceledError error enum is returned instead of QNetworkReply::TimeoutError. What is wrong? Am i doing something wrong or is it Qt bug?
From documentation that error should be if "the operation was canceled via calls to abort() or close() before it was finished."
I see no reason for that.
QByteArray encodedData = data.toUtf8();
QUrl url("http://myapi/jsonrpc");
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QNetworkAccessManager manager;
manager.setTransferTimeout(500);
QNetworkReply* reply = manager.post(request, encodedData);
QEventLoop loop;
connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
if (reply->error() != QNetworkReply::NoError) {
QString errorMsg = QString("HTTP Network request has failed. Code: ") + QVariant::fromValue(reply->error()).toString();
delete reply;
// error
// here i got QNetworkReply::OperationCanceledError
}
QByteArray response = reply->readAll();
//ok

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();
}

QNetworkReply::NetworkError(ProtocolUnknownError)

In my project, I am attempting to download a YouTube profile picture. The YouTube API returns this link https://yt3.ggpht.com/-7ipuUvDjVT8/AAAAAAAAAAI/AAAAAAAAAAA/hSPOcUsb1nw/s240-c-k-no-mo-rj-c0xffffff/photo.jpg
However, using the same function for downloading files from my own website doesn't work with this URL. I get QNetworkReply::NetworkError(ProtocolUnknownError) in the application output.
Here is my code:
QByteArray downloadFileData(QString url)
{
QNetworkRequest request;
request.setUrl(QUrl(url));
QNetworkReply *reply = manager->get(request);
QEventLoop loop;
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
if(reply->error() == QNetworkReply::NoError)
{
return reply->readAll();
}
else
{
qDebug() << reply->error();
}
reply->deleteLater();
return "";
}
When I pass that url to this function, I get that error. What is going on?
Thanks for your time

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);

How can I use Qt to get html code of the redirected page?

I'm trying to use Qt to download the html code from the following url:
http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=nucleotide&cmd=search&term=AB100362
this url will re-direct to
www.ncbi.nlm.nih.gov/nuccore/27884304
I try to do it by following way, but I cannot get anything.
it works for some webpage such as www.google.com, but not for this NCBI page. is there any way to get this page??
QNetworkReply::NetworkError downloadURL(const QUrl &url, QByteArray &data)
{
QNetworkAccessManager manager;
QNetworkRequest request(url);
QNetworkReply *reply = manager.get(request);
QEventLoop loop;
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
if (reply->error() != QNetworkReply::NoError)
{
return reply->error();
}
data = reply->readAll();
delete reply;
return QNetworkReply::NoError;
}
void GetGi()
{
int pos;
QString sGetFromURL = "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi";
QUrl url(sGetFromURL);
url.addQueryItem("db", "nucleotide");
url.addQueryItem("cmd", "search");
url.addQueryItem("term", "AB100362");
QByteArray InfoNCBI;
int errorCode = downloadURL(url, InfoNCBI);
if (errorCode != 0 )
{
QMessageBox::about(0,tr("Internet Error "), tr("Internet Error %1: Failed to connect to NCBI.\t\nPlease check your internect connection.").arg(errorCode));
return "ERROR";
}
}
That page appears to have a redirect.
From the Qt docs for 4.6:
Note: When the HTTP protocol returns a
redirect no error will be reported.
You can check if there is a redirect
with the
QNetworkRequest::RedirectionTargetAttribute
attribute.