您的位置:首页 > 编程语言 > C语言/C++

使用C++下载网页文件

2016-10-26 22:32 176 查看
C++程序实现翻墙。翻墙主要原理是更改hosts方式实现,目标hosts文件可以通过github上的文件获得。C++下载网页到指定目录文件的方法,并替换本地hosts即可。

具体示例:

Gate.h

class Gate
{
public:
Gate()=default;
~Gate()=default;
void getHttpFile(const char *saveFileName);
private:
const char * webAddr = "https://raw.githubusercontent.com/racaljk/hosts/master/hosts";
void downloadAndChange(const char *saveFileName);

};


Gate.cpp

#include "Gate.h"
#include<afx.h>
#include<afxinet.h>
#include<iostream>

void Gate::getHttpFile(const char *saveFileName){
this->downloadAndChange(saveFileName);
}
void Gate::downloadAndChange(const char *saveFileName){
CInternetSession Session(_T("lpload"));
Session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 5000);
Session.SetOption(INTERNET_OPTION_SEND_TIMEOUT, 5000);
Session.SetOption(INTERNET_OPTION_RECEIVE_TIMEOUT, 5000);
Session.SetOption(INTERNET_OPTION_DATA_SEND_TIMEOUT, 5000);
Session.SetOption(INTERNET_OPTION_DATA_RECEIVE_TIMEOUT, 5000);
DWORD dwFlag = INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_RELOAD;

CHttpFile *cFile;
char *pBuf = NULL;
int nBufLen = 0;
do
{
cFile = (CHttpFile*)Session.OpenURL((CString)webAddr, 1, dwFlag);
DWORD dwStatusCode;
cFile->QueryInfoStatusCode(dwStatusCode);
if (dwStatusCode == HTTP_STATUS_OK){
DWORD nLen = 0;
cFile->QueryInfo(HTTP_QUERY_CONTENT_LENGTH, nLen);
nBufLen = nLen;
if (nLen <= 0)break;
pBuf = (char *)malloc(nLen + 8);
ZeroMemory(pBuf, nLen + 8);
char *p = pBuf;
while (nLen > 0){
int n = cFile->Read(p, (nLen < 2048) ? nLen : 2048);
if (n <= 0)break;
p += n;
nLen -= n;
}
if (nLen != 0)break;
CFile file((CString)saveFileName, CFile::modeCreate | CFile::modeWrite);
file.Write(pBuf, nBufLen);
file.Close();
}

} while (0);
if (pBuf) {
free(pBuf);
pBuf = NULL;
nBufLen = 0;
}
if (cFile) {
cFile->Close();
Session.Close();
delete cFile;
}
}


main函数入口:

#include"Gate.h"
int main(){
Gate *m = new Gate();
m->getHttpFile("tmp.txt");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言
相关文章推荐