【C++】纯C++实现http打开网页下载内容的功能
2018-10-06 07:50
477 查看
#include "stdafx.h" #include <windows.h> #include <iostream> #include "Wininet.h" #pragma comment(lib,"Wininet.lib") using std::cout; using std::endl; //模拟浏览器发送HTTP请求函数 std::string HttpRequest(char * lpHostName, short sPort, char * lpUrl, char * lpMethod, char * lpPostData, int nPostDataLen) { HINTERNET hInternet, hConnect, hRequest; BOOL bRet; std::string strResponse; hInternet = NULL; hConnect = NULL; hRequest = NULL; 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; }
这是一个函数,只要调用这个函数,就可以获取网页的内容
调用方法
int main() { //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")); std::string strResponse = HttpRequest("www.qsxck.com", 80, "/", "GET", NULL, 0); //cout << strResponse.c_str(); FILE * fp; errno_t t = fopen_s(&fp,"D:\\old.html", "w"); fwrite(strResponse.c_str(),1, strResponse.length(), fp); fclose(fp); getchar(); return 0; }
相关文章推荐
- 使用BOOST实现简单的HTTP网页下载
- 实现自动发帖,注册。以及访问网页,执行网页下载等等功能
- <C/C++> Socket编程Http下载的简单实现
- [Winhttp]_[C/C++]_[使用win32 SDK的Windows HTTP Services(WinHTTP)通过代理下载网页]
- HTTP代理实现请求报文的拦截与篡改2--功能介绍+源码下载
- Java servlet 简单实现http文件下载断点续传功能
- socket http编程(用socket编程实现http网页下载)
- HTTP代理实现请求报文的拦截与篡改2--功能介绍+源码下载
- C/C++程序实现通过http代理访问网页内容
- 使用ASIHTTPRequest实现下载功能
- 采用linux下java http实现下载功能
- 打开网页出现http://xxx.eh7.biz/error.htm恶意广告被拦截,无法看到网站内容,请高手解决?
- Servlet实现将图片写入到网页和实现图片下载的功能
- HTTP代理实现请求报文的拦截与篡改9--实现篡改功能后的演示+源码下载
- 使用c++技术实现下载网页
- 用C++实现下载文件的功能
- 使用BOOST实现简单的HTTP网页下载
- 在窗体上放置一个标签、一个按钮、一个fontDialog控件。标签内容改为“烟台大学”。实现功能:1)程序运行时,单击打开字体对话框按钮,可选择字体,并以所选字体作为标签字体。
- fstream提供了三个类,用来实现c++对文件的操作。(文件的创建、读、写)。 ifstream -- 从已有的文件读 ofstream -- 向文件写内容 fstream - 打开文件供读写
- [Winhttp]_[C/C++]_[使用win32 SDK的Windows HTTP Services(WinHTTP)通过代理下载网页]