How to Perform HTTP GET in C#
Suppose you have a Web resource that you want to download programmatically (as opposed to doing it manually from a Web browser) from C#. The first thing you need to do is send an HTTP request to the server with the URL (e.g. http://www.google.com). The server will then process the request and send an HTTP response back, which needs to be processed. The following code can handle these things. Plus you have to handle it a little differently if you’re downloading a String/text document or a binary document (such as a PDF file or image). Note: It’s not necessary to use a CookieContainer, but it’s in there if you need it.
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; namespace Piccolo.Common { public class HttpHelper { private string _baseUrl; private CookieContainer _cookieContainer = new CookieContainer(); public HttpHelper() : this("") { } public HttpHelper(string baseUrl) { _baseUrl = baseUrl; } public string HttpStringGet(string relativeUrl) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(_baseUrl + relativeUrl); req.CookieContainer = _cookieContainer; return ReadBasicResponse(req.GetResponse()); } public byte[] HttpBinaryGet(string relativeUrl) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(_baseUrl + relativeUrl); req.CookieContainer = _cookieContainer; byte[] result = null; byte[] buffer = new byte[4096]; using (WebResponse resp = req.GetResponse()) using (Stream responseStream = resp.GetResponseStream()) using (MemoryStream memoryStream = new MemoryStream()) { int count = 0; do { count = responseStream.Read(buffer, 0, buffer.Length); memoryStream.Write(buffer, 0, count); } while (count != 0); result = memoryStream.ToArray(); } return result; } private string ReadBasicResponse(WebResponse response) { using (WebResponse resp = response) using (StreamReader sr = new StreamReader(resp.GetResponseStream())) return sr.ReadToEnd().Trim(); } } }
Here’s how you would call this to download an HTML document.
HttpHelper http = new HttpHelper(); string html = http.HttpStringGet("http://www.google.com/");
Here’s how you would call this to download a binary document.
HttpHelper http = new HttpHelper(); byte[] bytes = http.HttpBinaryGet("http://www.google.com/intl/en_ALL/images/logo.gif");
