C++模擬post HTTP編程

#include <iostream>
#include <string>
using namespace std;
#include <afxinet.h>

bool PostHttpPage(const std::string& hostname,
                                const std::string& pathname,
                                const std::string& postdata)
{
    CInternetSession session("your app agent name");

    try
    {
        INTERNET_PORT nPort = 80;
        DWORD dwRet=0;
        CHttpConnection * pServer = session.GetHttpConnection(hostname.c_str(),nPort);
        CHttpFile * pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST,pathname.c_str());
        CString strHeader = "Content-Type: application/x-www-form-urlencoded";  // 請求頭

        // 開始發送請求
        pFile->SendRequest(strHeader,(LPVOID)postdata.c_str(),postdata.size());
        pFile->QueryInfoStatusCode(dwRet);

        if (dwRet==HTTP_STATUS_OK)
        {
            CString strResult,strNewline;
            while(pFile->ReadString(strNewline))
            {// 循環讀取每行內容
                strResult += strNewline+"\r\n";
            }
            std::cout<<strResult<<std::endl;  // 顯示返回內容
        }
        else
        {
            return false;
        }
        delete pFile;
        delete pServer;
    }
    catch (CInternetException * e)
    {
        // catch errors from WinInet
        TCHAR pszError[200];
        e->GetErrorMessage(pszError,200);
        std::cout<<pszError<<std::endl;  // 顯示異常信息
        return false;
    }
    session.Close();

    return true;
}

int main(void)
{
    string postdata = "要提交的數據";
    PostHttpPage("IP地址","index.jsp?text=true",postdata);  // 測試
    //cout<<postdata<<endl;
    getchar();

    return 1;
}


發佈了43 篇原創文章 · 獲贊 5 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章