我正在开发一个Windows Phone 8应用程序,在我的应用程序中,我正在调用服务并将一些数据下载到我的应用程序中.
我正在使用httpwebrequest请求,但我无法设置超时到我的httpwebrequest对象.
这就是我创建和使用我的httpwebrequest的方式: –
public async Task<string> ServiceRequest(string serviceurl,string request,string methodname) { string response = ""; try { var httpwebrequest = WebRequest.Create(new Uri(serviceurl)) as HttpWebRequest; httpwebrequest.Method = "POST"; httpwebrequest.Headers["SOAPAction"] = "http://tempuri.org/" + iTestservice + "/" + methodname + ""; httpwebrequest.ContentType = "text/xml"; byte[] data = Encoding.UTF8.GetBytes(request); using (var requestStream = await Task<Stream>.Factory.FromAsync(httpwebrequest.BeginGetRequestStream,httpwebrequest.EndGetRequestStream,null)) { await requestStream.WriteAsync(data,data.Length); } response = await httpRequest(httpwebrequest); } catch (Exception ex) { return null; } return response; } public async Task<string> httpRequest(HttpWebRequest request) { string received; using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse,request.EndGetResponse,null))) { using (var responseStream = response.GetResponseStream()) { using (var sr = new StreamReader(responseStream)) { received = await sr.ReadToEndAsync(); } } } return received; }
我怀疑是: –
1)如何将超时属性设置为Httpwebrequest?
2)我可以在windows phone 8 app中设置超时属性的不同方式有哪些?
请告诉我 .
提前致谢.
您不能在Windows Phone上使用HttpWebRequest.Timeout,因为该平台不存在它.
原文链接:https://www.f2er.com/windows/372007.html如果您愿意使用测试版库,则可以安装HttpClient
via NuGet并使用其Timeout属性.
否则,您可能最好使用TaskEx.Delay,这是@L_404_1@的一部分.安装该库后,您将替换此行:
response = await httpRequest(httpwebrequest);
有了这个:
var httpTask = httpRequest(httpwebrequest); var completeTask = await TaskEx.WhenAny(httpTask,TaskEx.Delay(5000)); if (completeTask == httpTask) return await httpTask; else return null; // timeout