qt中使用winhttp发送服务端请求
qt中使用winhttp发送服务端请求
coder_life 发表于2年前
qt中使用winhttp发送服务端请求
  • 发表于 2年前
  • 阅读 10
  • 收藏 0
  • 点赞 0
  • 评论 0
摘要: 在qt项目开发中,其自身提供的QNetworkAccessManager在部分xp系统中,发出请求后会导致应用程序的无端退出,所以把请求和下载部分换成winhttp
/**

 * @brief HttpClient::HttpRequest

 * 发送服务器请求

 * @param url

 * @param header

 * @param data

 * @param type

 * @param timeout

 * @return

 */

QJsonObject HttpClient::HttpRequest(QString url,QString header, QByteArray data,QString type,int timeout)

{

    QJsonObject resultJson;//{"state":"false";"message"="errormsg"}

    resultJson["state"]=true;

    HINTERNET hSession = 0;

    HINTERNET hConnect = 0;

    HINTERNET hRequest = 0;

    WinHttpUrl winHttpUrl((LPCWSTR)url.constData());

    const char* strPostData= data.data();

    try{

        hSession = winHttpUrl.OpenSession(L"");

        if (hSession == NULL) {

            resultJson["state"]=false;

            resultJson["message"]="Error:Open session!";

        }

        hConnect = winHttpUrl.Connect(hSession, winHttpUrl.GetHostName(), winHttpUrl.GetPort());

        if (hConnect == NULL) {

            resultJson["state"]=false;

            resultJson["message"]="Error:Connect failed!";

        }

        if(type.isEmpty()){

            type="POST";

        }

        hRequest = winHttpUrl.OpenRequest(hConnect, (LPCWSTR)type.constData(), winHttpUrl.GetAllPath(), winHttpUrl.GetScheme());

        if (hRequest == NULL) {

            resultJson["state"]=false;

            resultJson["message"]="Error:OpenRequest failed!";

        }

        if(header.isEmpty()){

            header="content-type:application/octet-stream";

        }

        //header="Content-Length:"+QString::number(data.toStdString().length())+"\r\n"+header;

        //qDebug()<<header;

        if (!winHttpUrl.AddRequestHeaders(hRequest, (LPCWSTR)header.constData())) {

            resultJson["state"]=false;

            resultJson["message"]="Error:AddRequestHeaders failed!";

        }

        if(!winHttpUrl.SetTimeouts(hRequest,timeout*1000)){

            resultJson["state"]=false;

            resultJson["message"]="Error:SetTimeouts failed";

        }

        if (!winHttpUrl.SendRequest(hRequest, strPostData, data.length())) {

            resultJson["state"]=false;

            resultJson["message"]="Error:SendRequest failed!";

        }


        if (!winHttpUrl.EndRequest(hRequest)) {

            resultJson["state"]=false;

            resultJson["message"]="Error:EndRequest failed!";

        }

        if(resultJson["state"].toBool()){

            char szBuf[BUF_SIZE];

            DWORD dwSize = 0;

            szBuf[0] = 0;

            dwSize = BUF_SIZE;


            for (;;) {

                dwSize = BUF_SIZE;

                if (winHttpUrl.ReadData(hRequest, szBuf, dwSize, &dwSize) == FALSE) {

                    break;

                }

                if (dwSize <= 0) {

                    break;

                }

                szBuf[dwSize] = 0;

                resultJson["state"]=true;

                resultJson["message"]=szBuf;


            }

        }

    }

    catch (EXCEPTION_DEBUG_INFO e)

    {

        resultJson["state"]=false;

        resultJson["message"]="ERROR:winhttp Exception";

    }

    winHttpUrl.CloseInternetHandle(hRequest);

    winHttpUrl.CloseInternetHandle(hConnect);

    winHttpUrl.CloseInternetHandle(hSession);

    return resultJson;

}


/**
 * 下载文件
 * @brief HttpClient::DownLoadFile
 * @param Url
 * @return
 */
bool HttpClient::DownLoadFile(QString url,QString savePath)
{
    bool resultFlag=false;
    HINTERNET hSession = 0;
    HINTERNET hConnect = 0;
    HINTERNET hRequest = 0;

    WinHttpUrl winHttpUrl((LPCWSTR)url.constData());
    BYTE *pBuffer = NULL;
    DWORD dwReadBytes, dwSizeDW = sizeof(dwSizeDW), dwContentSize, dwIndex = 0;
    try{
        hSession = winHttpUrl.OpenSession(L"winhttp by joyinwise");
        if (hSession == NULL) {
            qDebug()<<"Error:Open session!";
        }
        hConnect = winHttpUrl.Connect(hSession, winHttpUrl.GetHostName(), winHttpUrl.GetPort());
        if (hConnect == NULL) {
            qDebug()<<"Error:Connect failed!";
        }
        // 创建一个请求,先查询内容的大小
        hRequest = WinHttpOpenRequest(hConnect, L"HEAD",winHttpUrl.GetAllPath(), L"HTTP/1.1", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_REFRESH);
        WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);
        WinHttpReceiveResponse(hRequest, 0);
        WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_CONTENT_LENGTH|WINHTTP_QUERY_FLAG_NUMBER, NULL, &dwContentSize, &dwSizeDW, &dwIndex);
        WinHttpCloseHandle(hRequest);
        // 创建一个请求,获取数据
        hRequest = WinHttpOpenRequest(hConnect, L"GET", winHttpUrl.GetAllPath(), L"HTTP/1.1", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_REFRESH);
        WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);
        WinHttpReceiveResponse(hRequest, 0);
        pBuffer = new BYTE[dwContentSize];
        ZeroMemory(pBuffer, dwContentSize);
        WinHttpReadData(hRequest, pBuffer, dwContentSize, &dwReadBytes);
        //写入文件
        HANDLE hFile = CreateFileW((LPCWSTR)savePath.constData(), GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
        WriteFile(hFile, pBuffer, dwContentSize, &dwReadBytes, NULL);
        CloseHandle(hFile);
        resultFlag=true;
    }
    catch(QString e){
        resultFlag=false;
        qDebug()<<e;
    }

    delete pBuffer;

    winHttpUrl.CloseInternetHandle(hRequest);
    winHttpUrl.CloseInternetHandle(hConnect);
    winHttpUrl.CloseInternetHandle(hSession);
    return resultFlag;
}


//调用示例
QJsonDocument doc;
            doc.setObject(reqParam);
            QByteArray byte_array = doc.toJson(QJsonDocument::Compact);
            //设置请求头
            QString headerStr="Content-Length:"+QString::number(byte_array.length())+"\r\n";
            headerStr+="Cache-Control:no-cache\r\n";
            headerStr+="content-type:application/json\r\n";
            headerStr+=AppProperty::userLoginInfo->PARAM_Token.toLocal8Bit()+":"+AppProperty::userLoginInfo->getToken().toLocal8Bit()+"\r\n";
            QJsonObject reply=HttpClient::HttpRequest(ActionURL::URL_API_HOST+"/"+interfaceName,headerStr,byte_array,"",20);

//下载
bool downloadResult = HttpFileDownloder::DownLoadFile(apk_url,downDBFileName.replace(".db",".zip"))


共有 人打赏支持
粉丝 2
博文 15
码字总数 3772
×
coder_life
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: