Mental Jetsam

By Peter Finch

Archive for January, 2011

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();

  return (response);

Posted in C#.NET | Leave a Comment »