Mental Jetsam

By Peter Finch

Binary HTTP GET in C#

Posted by pcfinch on January 13, 2011

The following code returns binary data (an array of bytes) from a HTTP GET request, and returns the mime type as a output parameter of the function.

public byte[] httpGetBytes(String url, out String mimeType)
{
  byte[] response = null;
  byte[] buffer = new byte[4096];
  int read;

  HttpWebRequest fetchReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
  fetchReq.Method = "GET";
  HttpWebResponse fetchResp = (HttpWebResponse)fetchReq.GetResponse();
  Stream responseStr = fetchResp.GetResponseStream();
  mimeType = fetchResp.ContentType;

  MemoryStream ms = new MemoryStream();
  while((read = responseStr.Read(buffer, 0, buffer.Length)) > 0)
    ms.Write(buffer, 0, read) ;
  response = ms.ToArray();

  fetchResp.Close();
  return (response);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: