简体   繁体   English

通过QNetworkAccessManager发布请求

[英]Post request via QNetworkAccessManager

I have a problem while working with an object of QNetworkAccessManager class. 使用QNetworkAccessManager类的对象时遇到问题。 I want to send a POST request to a web server. 我想向Web服务器发送POST请求。 My code is 我的代码是

 QNetworkAccessManager *manager; 
    manager = new QNetworkAccessManager (); 
    QNetworkRequest req; 
    req.setUrl(QUrl("http://example.com")); 
    //Configure the parameters for the post request: 
    QByteArray postData; 
    postData.append("Login=log_name&"); 
    postData.append("Password=some_pass"); 
    //Now create a QCookieJar: 
    manager->setCookieJar(new QNetworkCookieJar(manager)); 
    //Define the Request-url: 
    connect (manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinish (QNetworkReply  *))); 
    //Send the request: 
    manager->post(req, postData); 

The code of the used SLOT is: 使用过的SLOT的代码是:

void MainWindow::replyFinish(QNetworkReply *reply) 
   { 
    QString answer = QString::fromUtf8(reply->readAll()); 
     qDebug () << answer; 
   } 

The problem is that the answer is an empty string,but i believe it should be some html-code that describes acceptance or rejection of the authorization. 问题是答案是一个空字符串,但我相信它应该是一些描述接受或拒绝授权的html代码。

Thank you for your help. 谢谢您的帮助。

Most sites use a HTTP redirection after a login request (or after filling a form). 大多数站点在登录请求后(或填写表单后)使用HTTP重定向。 And you need to test for error in the same slot. 而且你需要在同一个插槽中测试错误。

You can handle redirections (and errors) with something similar to that code . 您可以使用与该代码类似的方式处理重定向(和错误)。

Since QNetworkAccessManager already create its own base QNetworkCookieJar object, you don't need to instantiate one if you didn't write a derived class or if you don't share a cookie jar with an other manager. 由于QNetworkAccessManager已经创建了自己的基本QNetworkCookieJar对象,因此如果您没有编写派生类或者没有与其他管理器共享cookie jar,则不需要实例化一个。 But you'll need to use the same manager (or the same cookie jar) for subsequent request to be able to reuse the cookies set by the server during the login. 但是您需要使用相同的管理器(或相同的cookie jar)来进行后续请求,以便能够在登录期间重用服务器设置的cookie。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM