Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

web services - How can I POST data to a url using QNetworkAccessManager

I have a webservice that I need to POST some data to using Qt. I figured that I can use a QByteArray when POSTing to the web service.

My question is, how can I format this array in order to be parsed correctly at the other end?

This is the code I have so far:

    // Setup the webservice url
    QUrl serviceUrl = QUrl("http://myserver/myservice.asmx");
    QByteArray postData;

   /* 
   Setup the post data somehow
   I want to transmit:
   param1=string,
   param2=string
   */

    // Call the webservice
    QNetworkAccessManager *networkManager = new QNetworkAccessManager(this);
    connect(networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(serviceRequestFinished(QNetworkReply*)));
    networkManager->post(QNetworkRequest(serviceUrl), postData);

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since some parameters and values might need to be utf-8 and percent encoded (spaces, &, =, special chars...), you should rather use QUrl (for Qt 4) or QUrlQuery (for Qt 5) to build the posted string.

Example code for Qt 4:

QUrl postData;
postData.addQueryItem("param1", "string");
postData.addQueryItem("param2", "string");
...
QNetworkRequest request(serviceUrl);    
request.setHeader(QNetworkRequest::ContentTypeHeader, 
    "application/x-www-form-urlencoded");
networkManager->post(request, postData.encodedQuery());

and for Qt 5:

QUrlQuery postData;
postData.addQueryItem("param1", "string");
postData.addQueryItem("param2", "string");
...
QNetworkRequest request(serviceUrl);
request.setHeader(QNetworkRequest::ContentTypeHeader, 
    "application/x-www-form-urlencoded");
networkManager->post(request, postData.toString(QUrl::FullyEncoded).toUtf8());

Starting with Qt 4.8 you can also use QHttpMultiPart if you need to upload files.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...