Posted By

dkirkland on 11/04/11


Tagged

http download


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

thastyle


Download text or bytes via HTTP


 / Published in: C#
 

URL: http://code.google.com/p/vitamink/source/browse/projects/snippets/trunk/src/VK.Snippets/HttpFetcher.cs

Downloads contents as a byte array or string, depending on need.

  1. namespace VK.Snippets
  2. {
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Net;
  6. using System.Text;
  7.  
  8. public static class HttpFetcher
  9. {
  10. public static string FetchPage(string url, string username = "", string password = "", string domain = "")
  11. {
  12. string page = Encoding.ASCII.GetString(FetchContent(url, username, password, domain));
  13.  
  14. return page;
  15. }
  16.  
  17. public static byte[] FetchContent(string url, string username = "", string password = "", string domain = "")
  18. {
  19. List<byte> contentBytes = new List<byte>();
  20.  
  21. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  22. if (username != "" && password != "" && domain != "")
  23. {
  24. request.Credentials = new NetworkCredential(username, password, domain);
  25. }
  26.  
  27. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  28. if (response.StatusCode == HttpStatusCode.OK)
  29. {
  30. Stream responseStream = response.GetResponseStream();
  31.  
  32. int b;
  33. while ((b = responseStream.ReadByte()) != -1)
  34. {
  35. contentBytes.Add((byte)b);
  36. }
  37. }
  38.  
  39. return contentBytes.ToArray();
  40. }
  41. }
  42. }

Report this snippet  

You need to login to post a comment.