HTTP request in C++ for BlackBerry 10

52 Views Asked by At

From this webpage, I have code.

When I use "http://httpbin.org/get", everything is OK.

But when I use my own url, for example "http://my-json-server.typicode.com/typicode/demo/db", I'm getting an error:

Unable to retrieve request headers

Where is my fault?

void RequestHeaders::getRequest()
{
    //const QUrl url("http://httpbin.org/get"); // OK
    const QUrl url("http://my-json-server.typicode.com/typicode/demo/db"); // Not OK

    QNetworkRequest request(url);

    QNetworkReply* reply = m_networkAccessManager->get(request);
    bool ok = connect(reply, SIGNAL(finished()), this, SLOT(onGetReply()));
    Q_ASSERT(ok);
    Q_UNUSED(ok);
}

void RequestHeaders::onGetReply()
{
    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());

    QString response;
    const QByteArray buffer(reply->readAll());

    bb::data::JsonDataAccess ja;
    const QVariant jsonva = ja.loadFromBuffer(buffer);
    const QMap<QString, QVariant> jsonreply = jsonva.toMap();

    QMap<QString, QVariant>::const_iterator it = jsonreply.find("headers");
    if (it != jsonreply.end()) {

        const QMap<QString, QVariant> headers = it.value().toMap();
        for (QMap<QString, QVariant>::const_iterator hdrIter = headers.begin();
            hdrIter != headers.end(); ++hdrIter) {
            if (hdrIter.value().toString().trimmed().isEmpty())
                continue;

            response += QString::fromLatin1("%1: %2\r\n").arg(hdrIter.key(),
            hdrIter.value().toString());
        }
    }

    for (it = jsonreply.begin(); it != jsonreply.end(); it++) {
        if (it.value().toString().trimmed().isEmpty())
            continue;

        response += QString::fromLatin1("%1: %2\r\n").arg(it.key(), it.value().toString());
    }

    reply->deleteLater();

    if (response.trimmed().isEmpty()) {
        response = tr("Unable to retrieve request headers");
    }

    emit complete(response);
}
1

There are 1 best solutions below

1
Remy Lebeau On

Your onGetReply handler is parsing the server's HTTP response body as JSON, searching it for a "headers" child field, and if found then extracts that child's own child fields into a local response variable.

http://httpbin.org/get responds with a JSON object containing a "headers" child object that has child fields in it. So your response variable ends up not being empty.

http://my-json-server.typicode.com/typicode/demo/db responds with a JSON object that does not contain any "headers" child. So your response variable is left empty.

You need to either:

  • fix your server to respond with JSON that actually matches what your code is expecting.

  • fix your onGetReply() code to handle the JSON that your server is actually sending.