我試圖創建一個函數,它接受一個url作爲參數,並返回從中獲得響應,它只是給我一個錯誤在WebResponse responseObject intialization
線如何使用異步做一個HTTP GET請求,並等待
唯一的例外是An exception of type 'System.Net.ProtocolViolationException' occurred in mscorlib.ni.dll but was not handled in user code
public static async Task<string> get(string url)
{
var request = WebRequest.Create(new Uri(url)) as HttpWebRequest;
request.Method = "GET";
request.ContentType = "application/json";
WebResponse responseObject = await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, request);
var responseStream = responseObject.GetResponseStream();
var sr = new StreamReader(responseStream);
string received = await sr.ReadToEndAsync();
return received;
}
外觀更容易寫:http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx – 2013-05-14 13:47:25
HTTP客戶端不支持在Windows Phone 8?! – mhyassin 2013-05-14 14:21:19
我不認爲這是異步,這是你的問題。 ProtocolViolationException指向的問題是'request.ContentType',這對於GET來說並不是預期的。 – 2013-05-14 15:27:55