博瑞博客

青春是一个充满活力的季节,即便是我们失去了天使的翅膀,只要我们还有一颗青春的心,那么我们的生活依然能够如阳光般灿烂!......
现在位置:首页 > C/C++ > C++的post请求(使用的是CInternetSession)

C++的post请求(使用的是CInternetSession)

江湖    C/C++    2018-11-7    2011    0评论
// WebPost.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

//int _tmain(int argc, _TCHAR* argv[])
//{
//  return 0;
//}

#include  <iostream>
#include  <string>
#include <afxinet.h> //定义了MFC CInternetSession类等   
bool PostHttpPage(const CString& hostName, const CString& 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(hostName, nPort); 
        CHttpFile* pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, pathName);   
        CString strHeaders = _T("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) 
{
    //向http://current.sinaapp.com/post.php发送数据
    PostHttpPage(_T("current.sinaapp.com"),_T("post.php"),"name=rain&age=12"); 
}

评论一下分享本文赞助博瑞

赞助博瑞X

扫码赞助博瑞
联系站长
博瑞博客
挤眼亲亲咆哮开心想想可怜糗大了委屈哈哈小声点右哼哼左哼哼疑问坏笑赚钱啦悲伤耍酷勾引厉害握手耶嘻嘻害羞鼓掌馋嘴抓狂抱抱围观威武给力
提交评论

清空信息
关闭评论