await Request
由于WP上对HTTP的请求都采用异步的方式,以下代码可以把它变成同步可等待的方式
public static string GetContentFromURL(string url) { var task = GetResult(url); return task.Result; } private static Task<string> GetResult(string url) { url = url.Replace("http://",""); url = "http://" + url; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.UserAgent = "Mozilla/5.0 (Linux; U; Android 4.0.3; de-ch; HTC Sensation Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"; Task<WebResponse> task = Task.Factory.FromAsync( request.BeginGetResponse, asyncResult => request.EndGetResponse(asyncResult), (object)null ); return task.ContinueWith(t => ReadStreamFromResponse(t.Result)); } private static string ReadStreamFromResponse(WebResponse response) { using (Stream responseStream = response.GetResponseStream()) using (StreamReader sr = new StreamReader(responseStream)) { //Need to return this response string strContent = sr.ReadToEnd(); return strContent; } }