如何使用异步做一个HTTP GET请求,并等待

问题描述:

我试图创建一个函数,它接受一个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

不能为GET请求设置ContentType,你是不是将任何数据发送到服务器。

Content-Type =请求主体的MIME类型(与POST和PUT请求一起使用)。

这是您的ProtocolViolationException的来源。

它看起来像你想设置Accept头。

接受=内容类型是可以接受的响应

(按Wikipedia

试着改变你的代码:以异步方法

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

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

与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