C# 使用共享的HTTPWebRequst属性

C# 使用共享的HTTPWebRequst属性,c#,httpwebrequest,C#,Httpwebrequest,设置HttpWebRequest后是否可以更改其URI?我之所以这么问,是因为如果您看到下面的代码,我正在设置CookieContainer和UserAgent。如果稍后在代码中将shared client属性设置为HttpWebRequest的新实例,是否需要重置UserAgent和CookieContainer 我想要共享HttpWebRequest属性的原因是,我不必每次发出请求时都设置这些变量 public MyAPI(String username, String password)

设置HttpWebRequest后是否可以更改其URI?我之所以这么问,是因为如果您看到下面的代码,我正在设置CookieContainer和UserAgent。如果稍后在代码中将shared client属性设置为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.
}
publicmyapi(字符串用户名、字符串密码)
{
this.username=用户名;
this.password=密码;
this.cookieContainer=新的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;
}
专用异步任务initLoginTokens()
{
使用(WebResponse=await client.GetResponseAsync())
使用(Stream responseStream=response.GetResponseStream())
使用(StreamReader stream=新StreamReader(responseStream))
{
CsQuery.CQ dom=CsQuery.CQ.Create(stream.ReadToEnd());
tt=dom.Select(“输入[name='tt']”)Attr(“值”);
dn=dom.Select(“输入[name='dn']”)Attr(“值”);
pr=dom.Select(“输入[name='pr']”)Attr(“值”);
如果(tt==null | | dn==null | | pr==null){
返回false;
}否则{
返回true;
}
}
}
公共异步任务LoginAsync()
{
如果(!wait initLoginTokens())
{
//抛出异常。未设置登录令牌。
}
//这里我需要发出另一个请求,但是如果可能的话,使用相同的HTTPWebRequest客户端。
}

否一旦设置,请求URI就无法更改。它是只读的。您必须重新初始化变量。

IIRC,HttpWebRequest只能用于一个请求,不能用于进一步的请求。除非您有充分的理由直接使用HttpWebRequest,否则我建议您使用(≥.净额1.1)或(≥.NET 4.5),两者都提供了一个很好的接口,可以根据需要创建HttpWebRequests,并且可以用于多个请求。关于HttpClient,我甚至不知道它的存在。谢谢你。