C++ POST方式訪問網頁


bool PostContent(CString strUrl, const CString &strPara, CString &strContent, CString &strDescript)//第一個參數為URL頭
{                         //第二個參數為要post表單的內容
    try{                       //第三個參數用於保存頁面返回的信息
                         //第四個參數用於記錄日志
        strDescript = "提交成功完成!";
        bool bRet = false;
        CString strServer, strObject, strHeader, strRet;
        unsigned short nPort;
        DWORD dwServiceType;
        if(!AfxParseURL www.90168.org (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: 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[256];
            memset(buffer, 0, 256);
            int nReadCount = 0;
            while((nReadCount = pFile->Read(buffer, 2048)) > 0)
            {
                strContent += buffer;
                memset(buffer, 0, 256);
            }
            bRet = true;
        }
        else
        {
            strDescript = "網站服務器錯誤" + strUrl;
            bRet = false;
        }
        ////////////////////////////////////////
        pFile->Close();
        sess.Close();
        return bRet;
    }
    catch(...)
    {
        int nCode = GetLastError();
        strDescript.Format("向服務器post失敗!錯誤號:%d", nCode);
        return false;
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM