qt 与服务器进行http(post)通信,传递的参数是json,
1.首先调用函数
void UBApplication::postHttpRequest()
{
QNetworkRequest request;
QNetworkAccessManager* naManager = new QNetworkAccessManager(this);
QObject::connect(naManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestFinished(QNetworkReply*)));
request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));
request.setUrl(QUrl("http://119.3.131.228:9001/logincontroller/login"));
QJsonObject obj1;
obj1.insert("password",loginPwd);
obj1.insert("username", loginName);
QByteArray byte_array = QJsonDocument(obj1).toJson();
qDebug()<< "user info " << obj1;
QNetworkReply* reply = naManager->post(request,byte_array);
}
2.完成时候调用槽函数
void UBApplication::requestFinished(QNetworkReply* reply)
{
QByteArray bytes = reply->readAll();
// 获取http状态码
QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
if(statusCode.isValid())
{
qDebug() << "status code=" << statusCode.toInt();
}
QNetworkReply::NetworkError err = reply->error();
if(err != QNetworkReply::NoError)
{
qDebug() << "Failed: " << reply->errorString();
}
else
{
// 获取返回内容
qDebug() << "loginResultJson is " << QString::fromStdString(bytes.toStdString());
loginResultJson = QString::fromStdString(bytes.toStdString());
//处理返回数据
}
}
3.需要注意的是,编码格式。
更多推荐
所有评论(0)