QT实现Json数组的Post发送

近日测试一个算法,算法提供的接口是发送Json数组格式的数据给后台服务,如果符合格式要求,则返回成功,否则返回格式错误。针对这个接口情况,计划采用QT实现Json数组元素额发送,整个实现过程比较曲折。首先是对方的接口设计文档描述不清楚,设计说要发送Json数据给后台服务器,所以首先选择的就是通过qt的QNetworkReply的post方法发送QByteArray数据给后台,结果调试了两天,怎么发送数据都是格式错误,很是郁闷。具体代码如下:

   QString urlstr = QString("http://%1:8086/xxxxxxxx").arg(ui->editServerIP->text());

    QString data;
    data.clear();
    data =QString(m_pCJsonData->getSndJsonByteArray());

    QNetworkRequest request;
    request.setUrl(QUrl(urlstr));

    request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json;charset=UTF-8"));
    //request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/x-www-form-urlencoded"));

    QNetworkReply *reply = m_pAccessManage->post(request, postdata.toUtf8());

    后来通过Wireshark网络抓包工具抓包示例程序与接口的通讯,发现通讯是这样的:


    通过抓包发现contentType不是发送的Json类型,而是普通的x-www-form-urlencoded类型,且发送是通过键值对的方式发送的,所以就按照改方式修改代码如下:

    QString urlstr = QString("http://%1:8086/xxxxxx").arg(ui->editServerIP->text());

    QString data;
    data.clear();
    data =QString(m_pCJsonData->getSndJsonByteArray());

    QString postdata = data.replace( 7, 1, "=");
    postdata = postdata.remove(1, 1);
    postdata = postdata.remove(postdata.length()-1, 1);
    postdata.append("\&\"isEnd\"=1");

    qDebug() << postdata << "=============" ;

    QNetworkRequest request;
    request.setUrl(QUrl(urlstr));

    //request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json;charset=UTF-8"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/x-www-form-urlencoded"));

    QNetworkReply *reply = m_pAccessManage->post(request, postdata.toUtf8());

修改完成以后,发送成功。

相关文章
相关标签/搜索