Created
November 21, 2019 06:49
-
-
Save FoxCouncil/8e77c021f1d568de32565c79a53f2392 to your computer and use it in GitHub Desktop.
Just give me head please...
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.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Net; | |
using System.Net.Security; | |
using System.Net.Sockets; | |
namespace FoxCouncil.Gist | |
{ | |
public static class Extensions | |
{ | |
public static Dictionary<string, string> GetHeaders(this WebClient webClient, string uri) | |
{ | |
const string HTTP_NEWLINE_CHAR = "\r\n"; | |
var uriParsed = new Uri(uri); | |
TcpClient tcpClient; | |
try | |
{ | |
tcpClient = new TcpClient(uriParsed.Host, uriParsed.Port); | |
} | |
catch (Exception) | |
{ | |
return null; | |
} | |
var headerData = System.Text.Encoding.ASCII.GetBytes( | |
$"GET {uriParsed.PathAndQuery} HTTP/1.1" + HTTP_NEWLINE_CHAR + | |
$"{HttpRequestHeader.Host}: {uriParsed.Host}" + HTTP_NEWLINE_CHAR + | |
$"{HttpRequestHeader.UserAgent}: {webClient.Headers[HttpRequestHeader.UserAgent] ?? "N/A"}" + HTTP_NEWLINE_CHAR + | |
$"{HttpRequestHeader.Connection}: close" + HTTP_NEWLINE_CHAR + | |
HTTP_NEWLINE_CHAR + HTTP_NEWLINE_CHAR); | |
Stream stream = tcpClient.GetStream(); | |
if (uriParsed.Scheme == Uri.UriSchemeHttps) | |
{ | |
var sslStream = new SslStream(stream); | |
sslStream.AuthenticateAsClient(uriParsed.Host); | |
stream = sslStream; | |
} | |
stream.Write(headerData, 0, headerData.Length); | |
var data = new byte[1024]; | |
var responseData = string.Empty; | |
Queue<string> rawHeaders; | |
while (true) | |
{ | |
responseData += System.Text.Encoding.ASCII.GetString(data, 0, stream.Read(data, 0, data.Length)); | |
if (responseData.Contains(HTTP_NEWLINE_CHAR + HTTP_NEWLINE_CHAR)) | |
{ | |
stream.Close(); | |
tcpClient.Close(); | |
rawHeaders = new Queue<string>(responseData.Split(HTTP_NEWLINE_CHAR + HTTP_NEWLINE_CHAR)[0].Split(HTTP_NEWLINE_CHAR)); | |
break; | |
} | |
} | |
var httpStatusCode = int.Parse(rawHeaders.Dequeue().Split(' ')[1]); | |
if ((HttpStatusCode)httpStatusCode == HttpStatusCode.OK) | |
{ | |
var headers = new Dictionary<string, string>(); | |
while (rawHeaders.Any()) | |
{ | |
var headerLine = rawHeaders.Dequeue().Split(": ", 2); | |
headers.Add(headerLine[0], headerLine[1]); | |
} | |
return headers; | |
} | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment