C++ post方式请求网页

来源:互联网 发布:云计算的重要应用 编辑:程序博客网 时间:2024/05/21 06:42

C++post方式向页面发送数据,用于记录程序中的一些操作。

bool PostHttpPage(const std::string& hostName, const std::string& pathName, const std::string& postData){    using namespace std;    CInternetSession session(_T("your app agent name"));    try    {        INTERNET_PORT nPort = 80;        DWORD dwRet = 0;        CHttpConnection* pServer = session.GetHttpConnection((LPCTSTR)hostName.c_str(), nPort);        CHttpFile* pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, (LPCTSTR)pathName.c_str());        CString strHeaders = "Content-Type: application/x-www-form-urlencoded"; // 请求头        //开始发送请求        pFile->SendRequest(strHeaders, (LPVOID)postData.c_str(), postData.size());        pFile->QueryInfoStatusCode(dwRet);        if (dwRet == HTTP_STATUS_OK)        {            CString result, newline;            while (pFile->ReadString(newline))            {//循环读取每行内容                result += newline + "\r\n";            }            std::cout << result << std::endl;//显示返回内容        }        else        {            return false;        }        delete pFile;        delete pServer;    }    catch (CInternetException* pEx)    {        //catch errors from WinInet        TCHAR pszError[200];        pEx->GetErrorMessage(pszError, 200);        std::cout << pszError << std::endl;//显示异常信息        return false;    }    session.Close();    return true;}

测试程序

int main(void){    Json::Value parameter,content;    parameter["Logstore"] = "test";    content["name"] = "22";    content["act"] = "222222";    parameter["Content"] = content;    parameter["Topic"] = "testtest";    std::string param = "parameter=" + parameter.toStyledString();    PostHttpPage("127.0.0.1", "/index.php?c=index&a=addlog", param);}
0 0
原创粉丝点击