您的位置:首页 > 理论基础 > 计算机网络

【RLIB】C++调用HttpRequest 、HttpResponse下载远程HTTP/HTTPS资源

2012-03-10 16:33 218 查看
void DownloadFromInternet(const System::String &Url, const System::String &SavePath)
{
	//创建 HttpRequest 请求对象  
	ManagedObject<System::Net::HttpRequest> request =
		new System::Net::HttpRequest(Url);
	if (request.IsNull()) {
		//throw new System::Exception::GetLastException();
		return;
	}

	//初始化HttpRequest
	request->Method    = _T("GET");
	request->Timeout   = 8000;
	request->UserAgent = _T("RLib Downloader/4.5 http://rlib.cf/"); 	request->Accept    = _T("text/xml,application/xml,application/xhtml+xml,text/html;*/*");
	request->Headers.Add("Accept-Charset", "iso-8859-1,utf-8;q=0.7,*;q=0.7");
	request->Headers.Add("Accept-Language", "zh-cn, zh;q=1.0,en;q=0.5,en;q=0.5,en;q=0.5");
	request->Headers.Add("Accept-Encoding", "gzip, deflate, x-gzip, identity; q=0.9");

	//获取远程服务器响应对象  
	System::Net::HttpResponse *response = request->GetResponse();
	
	//自动回收响应对象
	AutoRunOnce responseFinalizer([](void *response){
		reinterpret_cast<System::Net::HttpResponse>(response)->Close();
	}, response);

	//判断是否出现异常, 出于性能考虑, RLib框架本身并不使用SEH和C++异常处理, 需要自行抛出异常
	if (!response){
		RLIB_ALERT(request->GetLastException()->Message);
		//throw request->GetLastException();
		return;
	}
	if (response->GetLastException()->Id != STATUS_SUCCESS){
		//通常情况下是网页数据异常
		RLIB_ALERT(response->GetLastException()->Message);
		//throw new System::Net::HttpException(*response->GetLastException());
		return;
	}

	//成功 
	ManagedObject<System::IO::FileStream> output =
		System::IO::File::Create(SavePath, System::IO::File::CreateNewMode);
	if (output.IsSatisfied())
	{
		//response->GetResponseStream()->CopyTo(output);
		output->Write(response->GetResponseStream()->ObjectData,
					  response->GetResponseStream()->Length);

		//文件IO异常
		if (output->GetLastException()->Id != STATUS_SUCCESS)
		{
			RLIB_ALERT(output->GetLastException()->Message);
			//throw new System::IO::FileException(*response->GetLastException());
			return;
		}
	}
}


调用例子:

DownloadFromInternet(_T("http://rlib.cf/images/logo.png"), _T("logo.png"));


或者, 更简单的, 使用封装好的方法:

System::Net::WebClient::DownloadFile(const String &Url, const String &FilePath,
    HttpRequest *pRequest IN = nullptr,
    HttpResponse **ppResponse OUT = nullptr);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐