我正在尝试使用 System.Net.HttpWebRequest 类对特定 Web 服务器执行 HTTP GET 请求,以实现我们在众多服务器上进行负载平衡的 Web 应用程序。为了实现这一点,我需要能够为请求设置 Host 标头值,并且我已经能够通过使用 System.Net.WebProxy 类来实现这一点。
但是,当我尝试使用 SSL 执行 GET 时,这一切都崩溃了。当我尝试执行此操作时,对 HttpWebRequest.GetResponse 的调用会引发 System.Net.WebException,HTTP 状态代码为 400(错误请求)。
我试图通过 HttpWebRequest 实现的目标是可能的,还是我应该寻找一种替代方法来执行我想要的?
这是我一直用来尝试让这一切正常工作的代码:-
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);
}
}
}
}