我如何在Windows Phone上刷新HttpWebRequest对象
本文关键字:刷新 HttpWebRequest 对象 Phone Windows | 更新日期: 2023-09-27 18:19:12
我正在写一个windows phone应用程序,我需要做一个http请求。这个请求返回给我一个随机值,它总是在我请求它的url时改变。
所以我有一个带有按钮的应用程序,当我点击它时,我收到我想要的随机值,但是,如果我再次点击按钮,我收到相同的随机值!我在服务器端设置了一个断点,它只到达一次,如果点击按钮10次,它将第一次到达断点!!我需要每当我点击按钮,我有一个新的随机值!
我需要使用CookieContainer,因为在我的服务器上,我需要在这个会话中保持一些对象的定义。如果我不使用CookieContainer,我就不能保持会话,所以当我调用第二个请求时,那里就没有对象了。
private async Task<string> requestURLData(HttpWebRequest request)
{
HttpWebResponse response = (HttpWebResponse) await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, request);
var responseStream = response.GetResponseStream();
var sr = new StreamReader(responseStream);
string received = await sr.ReadToEndAsync();
return received;
}
private async Task<string> requestUrl(string url, CookieContainer cookie)
{
var request = WebRequest.Create(new Uri(url)) as HttpWebRequest;
request.CookieContainer = cookie;
return await this.requestURLData(request);
}
private async Button_Click(object sender, RoutedEventArgs e)
{
CookieContainer cookie = new CookieContainer();
var result = await this.requestUrl(this.urlBase + "getRandomNum", cookie);
result = await this.requestUrl(this.urlBase + "getAnotherValue", cookie);
}
您遇到了响应缓存-在您的url的末尾添加一个随机字符串,您的服务器会忽略它,以保证您不会命中缓存:
Random _rand = new Random();
private async Button_Click(object sender, RoutedEventArgs e)
{
CookieContainer cookie = new CookieContainer();
var result = await this.requestUrl(this.urlBase + "getRandomNum&rubbish=" + _rand.Next(), cookie);
...
}