0

设置后是否可以更改 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.
}
4

1 回答 1

0

否,请求 URI 设置后无法更改。它是只读的。您将不得不重新初始化您的变量。

于 2013-08-27T13:29:20.910 回答