Click here to Skip to main content
15,884,425 members
Articles / Programming Languages / C++/CLI

How to do Synchronous and Asynchronous web downloads

Rate me:
Please Sign up or sign in to vote.
4.83/5 (31 votes)
28 Jun 20024 min read 178.1K   1.3K   42  
Explains the usage of WebRequest, WebResponse and related classes.
/*
Author		: Nishant S
EMail		: nishforever@vsnl.com
Date		: June 28th 2002
Notes		: Demo app for Code Project article
*/
#include "stdafx.h"

#using <mscorlib.dll>
#using <system.dll>
#include <tchar.h>

using namespace System;
using namespace System::IO;
using namespace System::Net;
using namespace System::Threading;
using namespace System::Text;

__gc class WebStuffDemo
{
public:
	void DownloadFile(String* url, String* fpath)
	{
		WebRequest* wrq = WebRequest::Create(url);
		HttpWebResponse* hwr = static_cast<HttpWebResponse*>(wrq->GetResponse());
		Stream* strm = hwr->GetResponseStream();
		FileStream* fs = new FileStream(fpath,FileMode::Create,FileAccess::Write);
		BinaryWriter* br = new BinaryWriter(fs);
		int b;
		while((b=strm->ReadByte()) != -1)
		{
			br->Write(Convert::ToByte(b));
		}
		br->Close();
		strm->Close();
	}
	void DownloadFileAsync(String* url, String* fpath)
	{
		WebRequest* wrq = WebRequest::Create(url);
		finished = new ManualResetEvent(false);
		m_writeEvent = new AutoResetEvent(true);
		buffer = new unsigned char __gc[512];
		OutFile = new FileStream(fpath,
			FileMode::Create,FileAccess::Write);
		wrq->BeginGetResponse(
			new AsyncCallback(this,WebStuffDemo::ResponseCallback),
			wrq);
		finished->WaitOne();
		OutFile->Close();		
	}
private:
	ManualResetEvent* finished;
	AutoResetEvent* m_writeEvent;
	unsigned char buffer __gc[];
	FileStream* OutFile;
	void ResponseCallback(IAsyncResult* ar)
	{
		WebRequest* wrq = static_cast<WebRequest*>(ar->AsyncState);
		WebResponse* wrp = wrq->EndGetResponse(ar);		
		Stream* strm = wrp->GetResponseStream();
		strm->BeginRead(buffer,0,512,
			new AsyncCallback(this,WebStuffDemo::ReadCallBack),strm);
	}
	void ReadCallBack(IAsyncResult* ar)
	{
		Stream* strm = static_cast<Stream*>(ar->AsyncState);
		int count = strm->EndRead(ar);
		if(count > 0)
		{
			__wchar_t Temp __gc[] = new __wchar_t __gc[512];
			Decoder* d = Encoding::UTF8->GetDecoder();
			d->GetChars(buffer,0,buffer->Length,Temp,0);
			String* s = new String(Temp,0,count);
			Console::WriteLine(s->Length);
			unsigned char wbuff __gc[] = new unsigned char __gc[512];			
			
			buffer->CopyTo(wbuff,0);
			
			OutFile->BeginWrite(wbuff,0,count,
				new AsyncCallback(this,WebStuffDemo::WriteCallBack),OutFile);
			
			strm->BeginRead(buffer,0,512,
				new AsyncCallback(this,WebStuffDemo::ReadCallBack),strm);
		}
		else
		{
			strm->Close();
			finished->Set();
		}
	}
	void WriteCallBack(IAsyncResult* ar)
	{
		m_writeEvent->WaitOne();
		FileStream* out = static_cast<FileStream*>(ar->AsyncState);
		out->EndWrite(ar);
		m_writeEvent->Set();
	}

};

int _tmain(void)
{
	WebStuffDemo* wsd = new WebStuffDemo(); 
	wsd->DownloadFile("http://www.codeproject.com/styles/global.css",
		"d:\\global1.css");
	wsd->DownloadFileAsync("http://www.codeproject.com/styles/global.css",
		"d:\\global2.css");
    return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
Nish Nishant is a technology enthusiast from Columbus, Ohio. He has over 20 years of software industry experience in various roles including Chief Technology Officer, Senior Solution Architect, Lead Software Architect, Principal Software Engineer, and Engineering/Architecture Team Leader. Nish is a 14-time recipient of the Microsoft Visual C++ MVP Award.

Nish authored C++/CLI in Action for Manning Publications in 2005, and co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his WordPress blog. Nish is experienced in technology leadership, solution architecture, software architecture, cloud development (AWS and Azure), REST services, software engineering best practices, CI/CD, mentoring, and directing all stages of software development.

Nish's Technology Blog : voidnish.wordpress.com

Comments and Discussions