Skip to content

Instantly share code, notes, and snippets.

@MatthewLymer
Created March 7, 2018 17:24
Show Gist options
  • Save MatthewLymer/1db1b663a7218d0e6a4b18b8515fa22a to your computer and use it in GitHub Desktop.
Save MatthewLymer/1db1b663a7218d0e6a4b18b8515fa22a to your computer and use it in GitHub Desktop.
.NET Core send https request through proxy using sockets
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Matthew.Lymer.Tests
{
public sealed class HttpTests
{
private static readonly Encoding Utf8NoBom = new UTF8Encoding(false);
[Fact]
public async Task ShouldConnectToGoogleOverHttps()
{
using (var socket = new Socket(SocketType.Stream, ProtocolType.IP))
{
socket.NoDelay = true;
await socket.ConnectAsync(new DnsEndPoint("localhost", 8888));
using (var stream = new NetworkStream(socket, true))
{
using (var writer = new StreamWriter(stream, Utf8NoBom, 2048, true))
{
await writer.WriteAsync("CONNECT google.com:443 HTTP/1.1\r\n");
await writer.WriteAsync("Host: google.com:443\r\n");
await writer.WriteAsync("Connection: keep-alive\r\n");
await writer.WriteAsync("\r\n");
}
using (var reader = new StreamReader(stream, Utf8NoBom, false, 2048, true))
{
while (true)
{
var line = await reader.ReadLineAsync();
if (string.IsNullOrEmpty(line))
{
break;
}
}
}
using (var sslStream = new SslStream(stream, true))
{
await sslStream.AuthenticateAsClientAsync("google.com", null, SslProtocols.Tls11 | SslProtocols.Tls12, true);
using (var writer = new StreamWriter(sslStream, Utf8NoBom, 2048, true))
{
await writer.WriteAsync("GET / HTTP/1.1\r\n");
await writer.WriteAsync("Host: google.ca\r\n");
await writer.WriteAsync("Connection: close\r\n");
await writer.WriteAsync("Accept: */*\r\n");
await writer.WriteAsync("\r\n");
}
using (var reader = new StreamReader(sslStream, Utf8NoBom, false, 2048, true))
{
var response = await reader.ReadToEndAsync();
Assert.Contains("HTTP/1.1 301 Moved Permanently", response);
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment