How to post list of QString to HTTP sever



  • I can post one data to server

    QNetworkRequest request(QUrl("http://site.com/api/PtData/"));   request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));
        QByteArray const data( "\"152,2019/05/14,08:38:21\"");
        QNetworkAccessManager nam;
        QNetworkReply *reply = nam.post(request, data);
    

    now I want to post a list of data from text file like:

    "102,2019/05/15,08:38:21" "153,2019/05/15,08:38:21" "154,2019/05/15,08:38:21" "155,2019/05/15,08:38:21" ......
    

    I wrote this code but in post() should be const qbytearray ,how can I fix this?

    QNetworkRequest request(QUrl("http://site.comr/api/PtData"));
       request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
       QFile file_obj(":/new/prefix1/2.txt");
       if(!file_obj.open(QIODevice::ReadOnly)){
           qDebug()<<"Failed to open ";
       }
    
       QTextStream file_text(&file_obj);
      QString  json_string =file_text.readAll();
       file_obj.close();
       QStringList values = json_string.split(" ");
       QNetworkAccessManager nam;
       for(int u=0;u<20;u++){
       QNetworkReply *reply =nam.post(request,  values.at(u));
    .
    .
    .
     }
    }
    


  • https://doc.qt.io/qt-5/qstring.html#toUtf8

    values.at(u).toUtf8()
    also:
    for(int u=0;u<values.count();u++)
    


  • @zhmh said in How to post list of QString to HTTP sever:

    I want to post a list of data from text file like:

    Are you supposed to post a request per item or just only one request with the whole list?

    If the first is true, go with you have now (paying attention to @fcarney advice).

    If the latter is true, then you need to construct a JSON object (since you're stating "Content-Type" is JSON...) from the list and send that in the only request



  • @Pablo-J.-Rogina how should I to construct a JSON object from the list?can you show an example for the latter?



  • https://doc.qt.io/qt-5/qjsondocument.html#JsonFormat-enum

    QString json_string = "one,two,three,four,five,six";
    QByteArray joutput = QJsonDocument(QJsonArray::fromStringList(json_string.split(","))).toJson(QJsonDocument::Compact);
    

    Output:

    ["one","two","three","four","five","six"]
    

    Spend some time in the json docs. There are a few objects in there to be aware of.



  • @zhmh documentation is your friend...




Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.