Post JSON request in Qt 4.7

I'm working on a project required me to post JSON request to API server then receive data from server. However I cannot make it work. This is my code

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QUrl serviceUrl = QUrl("https://www.jusmine.jp/KA/KGBloginCheck");
    QNetworkRequest request(serviceUrl);
    QJsonObject json;
    json.insert("userid","xxxx");
    json.insert("userpass","xxxx");     
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader,QByteArray::number(json.size()));
    QNetworkAccessManager *networkManager = new QNetworkAccessManager(this);
    connect(networkManager,SIGNAL(finished(QNetworkReply*)),this,SLOT(serviceRequestFinish(QNetworkReply*)));
    networkManager->post(request,QJsonDocument(json).toJson());
}
void MainWindow::serviceRequestFinish(QNetworkReply *rep)
{
    QString strReply = (QString)rep->readAll();
    qDebug()<<"Test: "<<strReply;
}

After running the program I get nothing from server. (This code is built on Qt 4.7.0 so I have to use library qjson4-master). I don't know if any one can help me in this problem.

This is the result of testing server API: screenshot

Upvotes: 2

Views: 4637

Answers (1)

Mike
Mike

Reputation: 8355

You are calculating ContentLengthHeader in a wrong way:

request.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(json.size()));

Please note that QJsonObject::size() returns the number of (key,value) pairs stored in the object (not the length of its textual representation). Obviously, the header should equal the length of the content not its number of (key,value) pairs.

The code in your MainWindow's constructor should look something like this:

QUrl serviceUrl = QUrl("https://www.jusmine.jp/KA/KGBloginCheck");
QNetworkRequest request(serviceUrl);
QJsonObject json;
json.insert("userid","xxxx");
json.insert("userpass","xxxx");     
QJsonDocument jsonDoc(json);
QByteArray jsonData= jsonDoc.toJson();
request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
request.setHeader(QNetworkRequest::ContentLengthHeader,QByteArray::number(jsonData.size()));
QNetworkAccessManager networkManager;
connect(networkManager, SIGNAL(finished(QNetworkReply*)),
        this, SLOT(serviceRequestFinish(QNetworkReply*)));
networkManager.post(request, jsonData);

Side Note: There is no need to calculate Content-Length header yourself, Qt adds this header for you when you don't specify one, see implementation here. So, You can just omit the line where you add this header.


I want to get the status "200" from the server. How can I get that number ?

In your serviceRequestFinish slot, use QNetworkReply::attribute():

qDebug() << rep->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

This should print 200 if your request was ok.

Upvotes: 4

Related Questions