0
是否可以在設置HttpWebRequest後更改URI?我只問,因爲如果你看到我的代碼在下面,我設置CookieContainer和UserAgent。如果我稍後在代碼中將共享客戶端屬性設置爲HttpWebRequest的新實例,那麼我必須重置UserAgent和CookieContainer?使用共享HTTPWebRequst屬性
我想要一個共享的HttpWebRequest屬性的原因是,我不必每次發出請求都設置這些變量。
public MyAPI(String username, String password)
{
this.username = username;
this.password = password;
this.cookieContainer = new CookieContainer();
this.client = (HttpWebRequest)WebRequest.Create("http://mysite.com/api");
this.client.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0";
this.client.CookieContainer = this.cookieContainer;
}
private async Task<bool> initLoginTokens()
{
using (WebResponse response = await client.GetResponseAsync())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader stream = new StreamReader(responseStream))
{
CsQuery.CQ dom = CsQuery.CQ.Create(stream.ReadToEnd());
tt = dom.Select("input[name='tt']").Attr("value");
dn = dom.Select("input[name='dn']").Attr("value");
pr = dom.Select("input[name='pr']").Attr("value");
if (tt == null || dn == null || pr == null) {
return false;
} else {
return true;
}
}
}
public async Task<string> LoginAsync()
{
if(! await initLoginTokens())
{
// Throw exception. Login tokens not set.
}
// Here I need to make another request, but utilizing the same HTTPWebRequest client if possible.
}
IIRC,一個HttpWebRequest只能用於一個請求,不能再用於進一步的請求。除非你有充分的理由直接使用HttpWebRequest,否則我建議你使用[WebClient](http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx)(≥.NET 1.1)或[HttpClient](http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx)(≥.NET4.5),而這些都提供了一個很好的界面,照顧根據需要創建HttpWebRequests,並可用於多個請求。 – dtb
有趣的HttpClient我甚至不知道它存在。感謝那。 –