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

用到的头文件:

#include <QNetworkRequest>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QJsonObject>

代码实现:

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

展开阅读全文
©️2020 CSDN 皮肤主题: 1024 设计师: 上身试试 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值