I am trying to use the System.Net.HttpWebRequest class to perform a HTTP GET request to a specific web server for web applications we have load balanced over numerous servers. In order to achieve this, I need to be able to set the Host header value for the request, and I have been able to achieve this by using the System.Net.WebProxy class.
However, this all breaks down when I try to perform a GET using SSL. When I attempt to do this, the call to HttpWebRequest.GetResponse throws a System.Net.WebException, with a HTTP status code of 400 (Bad Request).
Is what I'm trying to achieve possible with HttpWebRequest, or should I be looking for an alternative way to perform what I want?
Here is the code I've been using to try and get this all to work :-
using System;
using System.Web;
using System.Net;
using System.IO;
namespace UrlPollTest
{
class Program
{
private static int suffix = 1;
static void Main(string[] args)
{
PerformRequest("http://www.microsoft.com/en/us/default.aspx", "www.microsoft.com");
PerformRequest("https://www.microsoft.com/en/us/default.aspx", "");
PerformRequest("https://www.microsoft.com/en/us/default.aspx", "www.microsoft.com");
Console.WriteLine("Press any key to continue");
Console.ReadKey();
}
static void PerformRequest(string AUrl, string AProxy)
{
Console.WriteLine("Fetching from {0}", AUrl);
try
{
HttpWebRequest request = WebRequest.Create(AUrl) as HttpWebRequest;
if (AProxy != "")
{
Console.WriteLine("Proxy = {0}", AProxy);
request.Proxy = new WebProxy(AProxy);
}
WebResponse response = request.GetResponse();
using (Stream httpStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(httpStream))
{
string s = reader.ReadToEnd();
File.WriteAllText(string.Format("D:\\Temp\\Response{0}.html", suffix++), s);
}
}
Console.WriteLine(" Success");
}
catch (Exception e)
{
Console.WriteLine(" " + e.Message);
}
}
}
}