首页 > 代码库 > C++发送HTTP请求---亲测可行(转)

C++发送HTTP请求---亲测可行(转)

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

环境:xp sp3,vs2008,在静态库中使用 MFC

[cpp] view plain copy
    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.   
    8. //模拟浏览器发送HTTP请求函数  
    9. std::string HttpRequest(char * lpHostName,short sPort,char * lpUrl,char * lpMethod,char * lpPostData,int nPostDataLen)  
    10. {  
    11.     HINTERNET hInternet,hConnect,hRequest;  
    12.   
    13.     BOOL bRet;  
    14.   
    15.     std::string strResponse;  
    16.   
    17.     hInternet = (HINSTANCE)InternetOpen("User-Agent",INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0);  
    18.     if(!hInternet)  
    19.         goto Ret0;  
    20.   
    21.     hConnect = (HINSTANCE)InternetConnect(hInternet,lpHostName,sPort,NULL,"HTTP/1.1",INTERNET_SERVICE_HTTP,0,0);  
    22.     if(!hConnect)  
    23.         goto Ret0;  
    24.   
    25.     hRequest = (HINSTANCE)HttpOpenRequest(hConnect,lpMethod,lpUrl,"HTTP/1.1",NULL,NULL,INTERNET_FLAG_RELOAD,0);  
    26.     if(!hRequest)  
    27.         goto Ret0;  
    28.   
    29.     //bRet = HttpAddRequestHeaders(hRequest,"Content-Type: application/x-www-form-urlencoded",Len(FORMHEADERS),HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);  
    30.     //if(!bRet)  
    31.         //goto Ret0;  
    32.   
    33.     bRet = HttpSendRequest(hRequest,NULL,0,lpPostData,nPostDataLen);  
    34.     while(TRUE)  
    35.     {  
    36.         char cReadBuffer[4096];  
    37.         unsigned long lNumberOfBytesRead;  
    38.         bRet = InternetReadFile(hRequest,cReadBuffer,sizeof(cReadBuffer) - 1,&lNumberOfBytesRead);  
    39.         if(!bRet || !lNumberOfBytesRead)  
    40.             break;  
    41.         cReadBuffer[lNumberOfBytesRead] = 0;  
    42.         strResponse = strResponse + cReadBuffer;  
    43.     }  
    44.   
    45.  Ret0:  
    46.     if(hRequest)  
    47.         InternetCloseHandle(hRequest);  
    48.     if(hConnect)  
    49.         InternetCloseHandle(hConnect);  
    50.     if(hInternet)  
    51.         InternetCloseHandle(hInternet);  
    52.   
    53.     return strResponse;  
    54. }  
    55.   
    56. void main()   
    57. {   
    58.     //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"));  
    59.     std::string strResponse = HttpRequest("www.hao123.com",80,NULL,"GET",NULL,0);  
    60.     FILE * fp = fopen("C:\\123.htm","wb");  
    61.     fwrite(strResponse.c_str(),strResponse.length(),1,fp);  
    62.     fclose(fp);  

C++发送HTTP请求---亲测可行(转)