Qt通过http连接企业微信群机器人发送消息

用到的头文件:

#include 
#include 
#include 
#include 

代码实现:

void httpConnectWeChatRobot(QString url, QString msg)	//url为群机器人的webhook,msg为要发的信息
{
    if(msg.isEmpty())
    {
        QMessageBox::about(this, "Error", QString::fromLocal8Bit("信息不能为空!"));
        return;
    }
    if(url.isEmpty())
    {
        QMessageBox::about(this, "Error", QString::fromLocal8Bit("url不能为空!"));
        return;
    }
    
    QJsonObject Msg, text;
    //QString total = QString::fromLocal8Bit("%1").arg(msg);	//如果信息包含中文时可能需要fromLocal8Bit进行转码
    text.insert("content", msg);	//text.insert("content", total);
    Msg.insert("text", text);
    Msg.insert("msgtype", "text");
    QJsonDocument document = QJsonDocument(Msg);
    QByteArray qByteHttpData = document.toJson();	//构造出机器人能够识别的json格式
    /*
	{
		"msgtype" : "text",
		"text" : {
			"content" : "msg的内容"
		}
	}
	*/

    QNetworkAccessManager m_pHttpMgr;
    QNetworkRequest requestInfo;
    requestInfo.setUrl(QUrl(url));
    requestInfo.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json; encoding=utf-8"));

    QNetworkReply *reply =  m_pHttpMgr.post(requestInfo, qByteHttpData);

    QEventLoop eventLoop;
    connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec();       //block until finish

    if (reply->error() == QNetworkReply::NoError)
    {
        QMessageBox::about(this, "Finish", "sent success!");
    }
    else
    {
        QString mes = QString("sent failed!\nError: %1").arg(reply->errorString());
        QMessageBox::about(this, "Error", mes);
    }
}

参考:
https://www.cnblogs.com/xupeidong/p/9506739.html

你可能感兴趣的:(Qt)