2013-06-27 138 views
2

我能夠通過實施類IWebProxy並執行此操作來使用代理: HttpClientHandler aHandler = new HttpClientHandler();使用WebProxy與HttpClient.SendAsync()和HttpRequestMessage

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. 

任何幫助表示讚賞,謝謝!

+0

什麼是NullReferenceException的調用堆棧?你確定它不在調用你的代理實現嗎? – TheESJ

回答

0

將它們直接添加到您的HttpClient。

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

謝謝,不知道這是可能的。但是,我也希望能夠生成不同類型的請求,例如發佈,放置,刪除,選項,跟蹤,獲取,頭像。我相信http客戶端只支持post,put,delete和get。 – KrispyDonuts

+0

@Ryan使用'SendAsync'和'new RequestMessage(){Method = new HttpMethod(「TRACE」)}' –

+0

謝謝Darrell!我會試試這個。 – KrispyDonuts

相關問題