1. 程式人生 > >C++傳送HTTP請求---親測可行(轉)

C++傳送HTTP請求---親測可行(轉)

轉自:http://hi.baidu.com/benbearlove/item/1671c23017575825b3c0c53f

環境:xp sp3,vs2008,在靜態庫中使用 MFC

  1. #include <afxwin.h>
  2. #include <stdio.h>
  3. #include <windows.h>
  4. #include <string>
  5. #include "Wininet.h"
  6. #pragma comment(lib,"Wininet.lib")
  7. //模擬瀏覽器傳送HTTP請求函式
  8. std::string HttpRequest(char * lpHostName,short sPort,
    char * lpUrl,char * lpMethod,char * lpPostData,int nPostDataLen)  
  9. {  
  10.     HINTERNET hInternet,hConnect,hRequest;  
  11.     BOOL bRet;  
  12.     std::string strResponse;  
  13.     hInternet = (HINSTANCE)InternetOpen("User-Agent",INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0);  
  14.     if(!hInternet)  
  15.         goto Ret0;  
  16.     hConnect = (HINSTANCE
    )InternetConnect(hInternet,lpHostName,sPort,NULL,"HTTP/1.1",INTERNET_SERVICE_HTTP,0,0);  
  17.     if(!hConnect)  
  18.         goto Ret0;  
  19.     hRequest = (HINSTANCE)HttpOpenRequest(hConnect,lpMethod,lpUrl,"HTTP/1.1",NULL,NULL,INTERNET_FLAG_RELOAD,0);  
  20.     if(!hRequest)  
  21.         goto Ret0;  
  22.     //bRet = HttpAddRequestHeaders(hRequest,"Content-Type: application/x-www-form-urlencoded",Len(FORMHEADERS),HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
  23.     //if(!bRet)
  24.         //goto Ret0;
  25.     bRet = HttpSendRequest(hRequest,NULL,0,lpPostData,nPostDataLen);  
  26.     while(TRUE)  
  27.     {  
  28.         char cReadBuffer[4096];  
  29.         unsigned long lNumberOfBytesRead;  
  30.         bRet = InternetReadFile(hRequest,cReadBuffer,sizeof(cReadBuffer) - 1,&lNumberOfBytesRead);  
  31.         if(!bRet || !lNumberOfBytesRead)  
  32.             break;  
  33.         cReadBuffer[lNumberOfBytesRead] = 0;  
  34.         strResponse = strResponse + cReadBuffer;  
  35.     }  
  36.  Ret0:  
  37.     if(hRequest)  
  38.         InternetCloseHandle(hRequest);  
  39.     if(hConnect)  
  40.         InternetCloseHandle(hConnect);  
  41.     if(hInternet)  
  42.         InternetCloseHandle(hInternet);  
  43.     return strResponse;  
  44. }  
  45. void main()   
  46. {   
  47.     //CString strResponse = HttpRequest("translate.google.com",80,"/translate_t?langpair=en|zh-CN","POST","hl=zh-CN&ie=UTF-8&text=this is me&langpair=en|zh-CN",strlen("hl=zh-CN&ie=UTF-8&text=this is me&langpair=en|zh-CN"));
  48.     std::string strResponse = HttpRequest("www.hao123.com",80,NULL,"GET",NULL,0);  
  49.     FILE * fp = fopen("C:\\123.htm","wb");  
  50.     fwrite(strResponse.c_str(),strResponse.length(),1,fp);  
  51.     fclose(fp);  
  52. }