2013-05-14 115 views
-1

我試圖創建一個函數,它接受一個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; 
} 
+0

外觀更容易寫:http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx – 2013-05-14 13:47:25

+0

HTTP客戶端不支持在Windows Phone 8?! – mhyassin 2013-05-14 14:21:19

+0

我不認爲這是異步,這是你的問題。 ProtocolViolationException指向的問題是'request.ContentType',這對於GET來說並不是預期的。 – 2013-05-14 15:27:55

回答

5

不能爲GET請求設置ContentType,你是不是將任何數據發送到服務器。

Content-Type =請求主體的MIME類型(與POST和PUT請求一起使用)。

這是您的ProtocolViolationException的來源。

它看起來像你想設置Accept頭。

接受=內容類型是可以接受的響應

(按Wikipedia

試着改變你的代碼:以異步方法

request.Accept = "application/json"; 
+0

謝謝你,我救了我;) – mhyassin 2013-05-15 14:50:26

1

與HttpClient的嘗試它,而不是像這樣:

public async Task<List<MyClass>> GetMyClassAsync(
    CancellationToken cancelToken = default(CancellationToken)) 
    { 
     using (HttpClient httpClient = new HttpClient()) 
     { 
      var uri = Util.getServiceUri("myservice"); 
      var response = await httpClient.GetAsync(uri, cancelToken); 
      return (await response.Content.ReadAsAsync<List<MyClass>>()); 
     } 
    } 
+0

Windows Phone 8不支持HTTPClient! – mhyassin 2013-05-14 14:01:48

+0

啊,我沒有看到windows-phone-8標籤,我的歉意 – Jammer 2013-05-14 14:40:18