1. 程式人生 > >CHttpFile POST方式提交資料並返回結果

CHttpFile POST方式提交資料並返回結果


bool PostContent(CString strUrl/*介面地址*/, const CString &strPara/*傳送資料*/, CString &strContent/*介面返回資料*/, CString &strDescript/*執行結果描述*/)
{
    try{
        strDescript = "提交成功完成!";
        bool bRet = false;
        CString strServer, strObject, strHeader, strRet;
        unsigned short nPort;
        DWORD dwServiceType;
        if(!AfxParseURL(strUrl, dwServiceType, strServer, strObject, nPort))
        {
            strDescript = strUrl + "不是有效有網路地址!";
            return false;
        }
        CInternetSession sess;//Create session

        CHttpFile* pFile;
        //////////////////////////////////////////////
        CHttpConnection *pServer = sess.GetHttpConnection(strServer, nPort); 
        if(pServer == NULL)
        {
            strDescript = "對不起,連線伺服器失敗!";
            return false;
        }
        pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST,strObject,NULL,1,NULL,NULL,INTERNET_FLAG_EXISTING_CONNECT); 
        if(pFile == NULL)
        {
            strDescript = "找不到網路地址" + strUrl;
            return false;
        }

//        pFile -> AddRequestHeaders("Content-Type: text/xml; charset=utf-8");
        pFile -> AddRequestHeaders("Content-Type: application/x-www-form-urlencoded"); 
        pFile -> AddRequestHeaders("Accept: */*"); 
        pFile -> SendRequest(NULL, 0, (LPTSTR)(LPCTSTR)strPara, strPara.GetLength()); 

        CString strSentence;
        DWORD dwStatus;
        DWORD dwBuffLen = sizeof(dwStatus);
        BOOL bSuccess = pFile->QueryInfo(
            HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,
            &dwStatus, &dwBuffLen);

        if( bSuccess && dwStatus>=  200 && dwStatus<300) 
        {
            char buffer[2049];
            memset(buffer, 0, 2049);
            int nReadCount = 0;
            while((nReadCount = pFile->Read(buffer, 2048)) > 0)
            {
                strContent += buffer;
                memset(buffer, 0, 2049);
            }
            bRet = true;
        }
        else
        {
            strDescript = "網站伺服器錯誤" + strUrl;
            bRet = false;
        }
        ////////////////////////////////////////
        pFile->Close();
        sess.Close();
        return bRet;
    }
    catch(...)
    {
        int nCode = GetLastError();
        strDescript.Format("向伺服器post失敗!錯誤號:%d", nCode);
        return false;
    }
}