Transferred from: http://hi.baidu.com/benbearlove/item/1671c23017575825b3c0c53f
Environment: XP sp3,vs2008, using MFC in a static library
[CPP]View PlainCopy
- #include <afxwin.h>
- #include <stdio.h>
- #include <windows.h>
- #include <string>
- #include "Wininet.h"
- #pragma comment (lib, "Wininet.lib")
- Impersonate the browser to send an HTTP request function
- std::string HttpRequest (char * lphostname, shortsPort,char * lpurl,char * lpmethod,char * lppostdata ,int npostdatalen)
- {
- Hinternet hinternet,hconnect,hrequest;
- BOOL BRet;
- Std::string strresponse;
- Hinternet = (hinstance) InternetOpen ("User-agent", internet_open_type_preconfig,null,null,0);
- if (!hinternet)
- Goto Ret0;
- Hconnect = (hinstance) internetconnect (Hinternet,lphostname,sport,null,"http/1.1", Internet_service_http, 0,0);
- if (!hconnect)
- Goto Ret0;
- Hrequest = (hinstance) httpopenrequest (Hconnect,lpmethod,lpurl,"http/1.1", Null,null,internet_flag_reload, 0);
- if (!hrequest)
- Goto Ret0;
- //bret = httpaddrequestheaders (hrequest, "content-type:application/x-www-form-urlencoded", Len (FORMHEADERS), Http_addreq_flag_replace | Http_addreq_flag_add);
- //if (!bret)
- //goto Ret0;
- BRet = HttpSendRequest (Hrequest,null,0,lppostdata,npostdatalen);
- While (TRUE)
- {
- Char creadbuffer[4096];
- unsigned long lnumberofbytesread;
- BRet = InternetReadFile (Hrequest,creadbuffer,sizeof (Creadbuffer)-1,&lnumberofbytesread);
- if (!bret | |!lnumberofbytesread)
- Break ;
- Creadbuffer[lnumberofbytesread] = 0;
- Strresponse = Strresponse + creadbuffer;
- }
- Ret0:
- if (hrequest)
- InternetCloseHandle (hrequest);
- if (hconnect)
- InternetCloseHandle (Hconnect);
- if (hinternet)
- InternetCloseHandle (hinternet);
- return strresponse;
- }
- void Main ()
- {
- //cstring strresponse = HttpRequest ("translate.google.com", "a", "/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 "));
- std::string strresponse = HttpRequest ("www.hao123.com", 80,null,"GET", null,0);
- FILE * fp = fopen ("c:\\123.htm","WB");
- Fwrite (Strresponse.c_str (), Strresponse.length (), 1,FP);
- Fclose (FP);
- }
C + + Send HTTP request---Pro-test feasible (RPM)