使用WebProxy和HttpClient.SendAsync()和HttpRequestMessage

时间:2013-06-27 21:09:16

标签: c# .net windows-store-apps dotnet-httpclient

我可以通过实现类IWebProxy并使用代理来执行此操作: HttpClientHandler aHandler = new HttpClientHandler();

aHandler.UseCookies = true;
aHandler.AllowAutoRedirect = true;
IWebProxy proxy = new AWProxy(new Uri("http://xx.xx.xxx.xxx:xxxx"));
proxy.Credentials = new NetworkCredential("xxxx", "xxxx");
aHandler.Proxy = proxy;

HttpClient client = new HttpClient(aHandler);

通过调用client.GetAsync(“http://google.com”),我能够获得成功的响应消息。但是我希望能够使用HttpRequestMessage来控制标题和发布/放置内容。

HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, uri); 

//add other headers
requestMessage.Headers.UserAgent.ParseAdd("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)");

HttpResponseMessage response = await client.SendAsync(requestMessage);

但是如果我使用HttpRequestMessage,我会得到这个例外:

System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: Unable to connect to the remote server. ---> System.NullReferenceException: Object reference not set to an instance of an object.

感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

将它们直接添加到您的HttpClient。

client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0;     Windows NT 6.2; WOW64; Trident/6.0)");