C++使用CHttpFile实现Http请求

来源:互联网 发布:dva的防御矩阵 编辑:程序博客网 时间:2024/05/18 21:42

C++实现http请求的代码,参照网上的修改了下在mfc中使用

1、HttpClient.h

[cpp] view plain copy
  1. //////////////////////////////////// HttpClient.h  
  2. #ifndef HTTPCLIENT_H  
  3. #define HTTPCLIENT_H  
  4.   
  5. #include <afxinet.h>  
  6. #include <string>  
  7. using namespace std;  
  8.   
  9. #define  IE_AGENT  _T("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)")  
  10.   
  11. // 操作成功  
  12. #define SUCCESS        0  
  13. // 操作失败  
  14. #define FAILURE        1  
  15. // 操作超时 www.it165.net  
  16. #define OUTTIME        2  
  17.   
  18. class CHttpClient  
  19. {  
  20. public:  
  21.     CHttpClient(LPCTSTR strAgent = IE_AGENT);  
  22.     virtual ~CHttpClient(void);  
  23.   
  24.     int HttpGet(LPCTSTR strUrl, LPCTSTR strPostData, CString &strResponse);  
  25.     int HttpPost(LPCTSTR strUrl, LPCTSTR strPostData, CString &strResponse);  
  26.     int HttpPut(LPCTSTR strUrl, LPCTSTR strPostData, CString &strResponse);  
  27.   
  28. private:  
  29.     int ExecuteRequest(int strMethod, LPCTSTR strUrl, LPCTSTR strPostData, CString &strResponse);  
  30.     void Clear();  
  31.       
  32.   
  33. private:  
  34.     CInternetSession *m_pSession;  
  35.     CHttpConnection *m_pConnection;  
  36.     CHttpFile *m_pFile;  
  37. };  
  38.   
  39. #endif // HTTPCLIENT_H  

2、HttpClient.cpp

[cpp] view plain copy
  1. ////////////////////////////////// HttpClient.cpp  
  2. #include "stdafx.h"  
  3. #include "HttpClient.h"  
  4.   
  5. #define  BUFFER_SIZE       1024  
  6.   
  7. #define  NORMAL_CONNECT             INTERNET_FLAG_KEEP_CONNECTION  
  8. #define  SECURE_CONNECT                NORMAL_CONNECT | INTERNET_FLAG_SECURE  
  9. #define  NORMAL_REQUEST             INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE   
  10. #define  SECURE_REQUEST             NORMAL_REQUEST | INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID  
  11.   
  12. CHttpClient::CHttpClient(LPCTSTR strAgent)  
  13. {  
  14.     m_pSession = new CInternetSession(strAgent);  
  15.     m_pConnection = NULL;  
  16.     m_pFile = NULL;  
  17. }  
  18.   
  19.   
  20. CHttpClient::~CHttpClient(void)  
  21. {  
  22.     Clear();  
  23.     if (NULL != m_pSession)  
  24.     {  
  25.         m_pSession->Close();  
  26.         delete m_pSession;  
  27.         m_pSession = NULL;  
  28.     }  
  29. }  
  30.   
  31. void CHttpClient::Clear()  
  32. {  
  33.     if (NULL != m_pFile)  
  34.     {  
  35.         m_pFile->Close();  
  36.         delete m_pFile;  
  37.         m_pFile = NULL;  
  38.     }  
  39.   
  40.     if (NULL != m_pConnection)  
  41.     {  
  42.         m_pConnection->Close();  
  43.         delete m_pConnection;  
  44.         m_pConnection = NULL;  
  45.     }  
  46. }  
  47.   
  48. int CHttpClient::ExecuteRequest(int strMethod, LPCTSTR strUrl, LPCTSTR strPostData, CString &strResponse)  
  49. {  
  50.     int result =FAILURE ;  
  51.     //WCHAR* wPostData = strPostData.GetBuffer();  
  52.     CString strServer;  
  53.     CString strObject;  
  54.     DWORD dwServiceType;  
  55.     INTERNET_PORT nPort;  
  56.   
  57.   
  58.     AfxParseURL(strUrl, dwServiceType, strServer, strObject, nPort);  
  59.     if (AFX_INET_SERVICE_HTTP != dwServiceType && AFX_INET_SERVICE_HTTPS != dwServiceType)  
  60.     {  
  61.         return FAILURE;  
  62.     }  
  63.   
  64.     try  
  65.     {  
  66.         m_pConnection = m_pSession->GetHttpConnection(strServer,  
  67.             dwServiceType == AFX_INET_SERVICE_HTTP ? NORMAL_CONNECT : SECURE_CONNECT,  
  68.             nPort);  
  69.         m_pFile = m_pConnection->OpenRequest(strMethod, strObject,  
  70.             NULL, 1, NULL, NULL,  
  71.             (dwServiceType == AFX_INET_SERVICE_HTTP ? NORMAL_REQUEST : SECURE_REQUEST));  
  72.   
  73.         /*设置请求相关参数*/  
  74.         m_pFile->AddRequestHeaders(L"Accept: */*,application/json");//accept请求报头域,表示客户端接受哪些类型的信息  
  75.         m_pFile->AddRequestHeaders(L"Accept-Charset:UTF8");  
  76.         m_pFile->AddRequestHeaders(L"Accept-Language: zh-cn;q=0.8,en;q=0.6,ja;q=0.4");  
  77.         m_pFile->AddRequestHeaders(L"Content-Type:application/json");//content为实体报头域,格式及编码  
  78.   
  79.         //m_pFile->SendRequest(NULL, 0, (LPVOID)(LPCTSTR)strPostData, strPostData == NULL ? 0 : _tcslen(strPostData));  
  80.   
  81.         /*请求body内容先转为UTF-8编码,与服务端保持一致,cword为要发送内容*/  
  82.         char*cword; //ANSI指针  
  83.         if (strPostData != NULL){  
  84.             DWORD  num = WideCharToMultiByte(CP_UTF8, 0, strPostData, -1, NULL, 0, NULL, NULL);//計算這個UNICODE实际由几个UTF-8字組成  
  85.             cword = (char*)calloc(num, sizeof(char));   //申请空间  
  86.             if (cword == NULL)                          //是否申请  
  87.             {  
  88.                 free(cword);  
  89.             }  
  90.             memset(cword, 0, num*sizeof(char));     //初始化  
  91.             WideCharToMultiByte(CP_UTF8, 0, strPostData, -1, cword, num, NULL, NULL);  
  92.             printf("content长度为%d\n", strlen(cword));  
  93.             m_pFile->SendRequest(NULL, 0, cword, strlen(cword));//发送请求  
  94.         }  
  95.         else{  
  96.             m_pFile->SendRequest(NULL, 0, NULL, 0);//发送请求  
  97.         }  
  98.           
  99.   
  100.         DWORD dwRet;  
  101.         m_pFile->QueryInfoStatusCode(dwRet);//查询执行状态  
  102.         printf("HTTP_STATUS_code:%d\n", dwRet);  
  103.         if (dwRet == HTTP_STATUS_OK){//http请求执行失败  
  104.             result = SUCCESS;  
  105.         }  
  106.   
  107.         /*保存http响应*/  
  108.         char szChars[BUFFER_SIZE + 1] = { 0 };  
  109.         string strRawResponse = "";  
  110.         UINT nReaded = 0;  
  111.         while ((nReaded = m_pFile->Read((void*)szChars, BUFFER_SIZE)) > 0)  
  112.         {  
  113.             szChars[nReaded] = '\0';  
  114.             strRawResponse += szChars;  
  115.             memset(szChars, 0, BUFFER_SIZE + 1);  
  116.         }  
  117.   
  118.         /*utf8转unicode*/  
  119.         int unicodeLen = MultiByteToWideChar(CP_UTF8, 0, strRawResponse.c_str(), -1, NULL, 0);  
  120.         WCHAR *pUnicode = new WCHAR[unicodeLen + 1];  
  121.         memset(pUnicode, 0, (unicodeLen + 1)*sizeof(wchar_t));  
  122.         MultiByteToWideChar(CP_UTF8, 0, strRawResponse.c_str(), -1, pUnicode, unicodeLen);  
  123.         strResponse = pUnicode;//最终响应结果  
  124.         //TRACE(strResponse + L"");  
  125.         delete[]pUnicode;  
  126.         pUnicode = NULL;  
  127.           
  128.         Clear();  
  129.     }  
  130.     catch (CInternetException* e)  
  131.     {  
  132.         Clear();  
  133.         DWORD dwErrorCode = e->m_dwError;  
  134.         e->Delete();  
  135.   
  136.         DWORD dwError = GetLastError();  
  137.   
  138.         printf("dwError = %d", dwError, 0);  
  139.   
  140.         strResponse = L"CInternetException\n";  
  141.   
  142.         if (ERROR_INTERNET_TIMEOUT == dwErrorCode)  
  143.         {  
  144.             return OUTTIME;  
  145.         }  
  146.         else  
  147.         {  
  148.             return FAILURE;  
  149.         }  
  150.     }  
  151.     return result;  
  152. }  
  153.   
  154. int CHttpClient::HttpGet(LPCTSTR strUrl, LPCTSTR strPostData, CString &strResponse)  
  155. {  
  156.     return ExecuteRequest(CHttpConnection::HTTP_VERB_GET, strUrl, NULL, strResponse);  
  157. }  
  158.   
  159. int CHttpClient::HttpPost(LPCTSTR strUrl, LPCTSTR strPostData, CString &strResponse)  
  160. {  
  161.     return ExecuteRequest(CHttpConnection::HTTP_VERB_POST, strUrl, strPostData, strResponse);  
  162. }  
  163. int CHttpClient::HttpPut(LPCTSTR strUrl, LPCTSTR strPostData, CString &strResponse)  
  164. {  
  165.     return ExecuteRequest(CHttpConnection::HTTP_VERB_PUT, strUrl, strPostData, strResponse);  
  166. }  
原创粉丝点击