Created
January 4, 2011 04:11
-
-
Save chrisforbes/764377 to your computer and use it in GitHub Desktop.
DownloadRaw -- it sucks less than WebClient.DownloadString
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Net; | |
using System.Net.Sockets; | |
using System.Text; | |
using System.Threading; | |
namespace wctest | |
{ | |
static class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var data = DownloadRaw("http://master.open-ra.org/VERSION"); | |
Console.WriteLine(Encoding.UTF8.GetString(data)); | |
var ev = new ManualResetEvent(false); | |
} | |
static byte[] DownloadRaw(string url) | |
{ | |
var uri = new Uri(url); | |
var ip = Dns.GetHostEntry(uri.DnsSafeHost).AddressList[0]; | |
using (var s = new TcpClient()) | |
{ | |
s.Connect(new IPEndPoint(ip, uri.Port)); | |
var ns = s.GetStream(); | |
var sw = new StreamWriter(ns); | |
sw.Write("GET {0} HTTP/1.1\r\nHost:{1}\r\n\r\n", uri.PathAndQuery, uri.Host); | |
sw.Flush(); | |
var br = new BinaryReader(ns); | |
var contentLength = 0; | |
for (; ; ) | |
{ | |
var result = br.ReadLine(); | |
var kv = result.Split( new string[] { ": " }, StringSplitOptions.RemoveEmptyEntries ); | |
if (result == "") | |
{ | |
/* data follows the blank line */ | |
if (contentLength > 0) | |
{ | |
var block = new byte[contentLength]; | |
br.Read(block, 0, contentLength); | |
s.Close(); | |
return block; | |
} | |
else | |
{ | |
s.Close(); | |
return new byte[] {}; | |
} | |
} | |
else if (kv[0] == "Content-Length") | |
contentLength = int.Parse(kv[1]); | |
} | |
} | |
} | |
static string ReadLine(this BinaryReader br) | |
{ | |
var sb = new StringBuilder(); | |
char c; | |
while( (c = br.ReadChar()) != '\n' ) | |
if (c != '\r' && c != '\n') | |
sb.Append(c); | |
return sb.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment