Make an HTTP request via #TCP over an Authenticated #proxy in C#
If you ever find yourself reverting to writing HTTP code using TCPClient, do a double-think, since there is very few situations where you genuinely need to resort to writing TCP/IP code. You can do an Authenticated proxy call using standard HTTP calls, by just setting the networkCredentials on a WebProxy class.
However, if you’ve read this caveat, and you still insist that you need to write code at TCP/IP level, then here’s some code that demonstrates how to make a simple HTTPS get request via an Authenticated HTTP Proxy (Luminati)
The authentication token, which I’ve omitted below, for obvious reasons is a base64 encoded version of your username : your password .
var tcp = new TcpClient(“zproxy.luminati.io”, 22225);
var stream = tcp.GetStream();var connect = Encoding.ASCII.GetBytes(“CONNECT icanhazip.com:443 HTTP/1.0\n” +
“proxy-authorization: Basic XXXXXX==\n\n”);
stream.Write(connect, 0, connect.Length);
var rawStream = new StreamReader(stream);
rawStream.ReadLine();
var ssl = new SslStream(stream);
ssl.AuthenticateAsClient(“www.icanhazip.com”, null, SslProtocols.Tls12, false);
var strPostString = “GET / HTTP/1.0\r\n” +
“Host:www.icanhazip.com\r\n” +
“\r\n”;
var send = Encoding.ASCII.GetBytes(strPostString);
ssl.Write(send, 0, send.Length);
var sr = new StreamReader(ssl);
var str = sr.ReadToEnd();
tcp.Close();
ssl.Close();
return str;