Making a #HTTP request via #TCP/IP in C#
Sometimes using WebClient or HttpClient hides important information on how you connect to a remote server. Recently I was getting a protocol violation error, when making a web request to a server. OK, so the remote server was misbehaving and sending me back corrupted HTTP headers, but I still wanted to see the response, but WebClient / HTTPRestponse was not showing me anything, just throwing an exception.
So, I resorted to TCPClient – Once again, I have to stress, this should be a last resort, you should never need to make HTTP requests using raw TCP/IP, anyway.
So, what I was trying to do, is get my remote IP address while going through a proxy, which should be the IP address of the proxy, as long as it is working correctly, and here’s the code;
private static void tcpconnect()
{
var tcp=new TcpClient(“**proxy IP***”,*** Proxy port ***);
var stream = tcp.GetStream();
var send = Encoding.ASCII.GetBytes(“GET http://www.icanhazip.com HTTP/1.0\r\n\r\n”);
stream.Write(send,0,send.Length);
var sr = new StreamReader(stream);
var str = sr.ReadToEnd();
Console.WriteLine(str);
tcp.Close();
stream.Close();
}
The Http 1.0 requires the server to close the TCP connection after the response is sent. HTTP 1.1 would keep the TCP connection open, so the ReadToEnd would hang. You could send Connection:close and use HTTP 1.1 if you wanted, or use a more intelligent stream reader.
If you’d like to know more about this subject, You can do worse than check out my book which is available here: Buy at Amazon US or Buy at Amazon UK
you’re using a tcp client. tanking awya all the magic
LikeLike