是否可以在设置后更改HttpWebRequest的URI?我只是问,因为如果你看到我的代码,我正在设置CookieContainer和UserAgent。如果我稍后在代码中将共享客户端属性设置为HttpWebRequest的新实例,我是否必须重置UserAgent和CookieContainer?
我想要一个共享的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.
}
答案 0 :(得分:0)
设置后,无法更改请求URI。它只读。您必须重新初始化变量。