在.NET4.5中的异步POST方法的HttpResponseMessage中的异常

时间:2012-04-04 21:41:58

标签: c# .net http windows-8 last.fm

我正在用C#开发Windows 8(Consumer Preview)的应用程序。它对Last.fm API进行简单的REST调用。

这个例外现在困扰着我很多天。我正在尝试向Last.fm API方法发送POST调用。但每当我发出电话时,我都会收到以下mssg -

  

“mscorlib.dll中发生了'System.Net.Http.HttpRequestException'类型的异常,但未在用户代码中处理”。   附加信息:发送请求时发生错误。

如果我打印出例外情况 -

  

System.Net.Http.HttpRequestException:发送请求时发生错误。 ---> System.Net.WebException:底层连接已关闭:连接意外关闭。

     

at System.Net.HttpWebRequest.EndGeetResponse(IAsyncResult asyncResult)

     

at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)

我对Gt调用last.fm的身份验证API工作正常。

我附上了一段代码:

private async void Collection_Click_1(object sender, RoutedEventArgs e)
{
    /* .
       .
       .
    */

HttpClient Cli = new HttpClient();
string track_updateNowPlaying = "method=track.updateNowPlaying&track=" + id3.Title + "&artist=" +id3.Artist + "&album=" + id3.Album + "&api_key=" + lfm_api_key + "&api_sig=" + updtrack_sig + "&sk=" + Globalv.session_key;

HttpContent tunp =new StringContent(track_updateNowPlaying);

try
{
    //getting exception in the following line
    HttpResponseMessage upd_now_playing = await cli.PostAsync(new Uri("http://ws.audioscrobbler.com/2.0/", UriKind.RelativeOrAbsolute), tunp);

}
catch(Exception ex) {textblock.text = ex.ToString();}
}

private async void LoginBtn_Click_1(object sender, RoutedEventArgs e) //this function is called before collection_click_1 function
{
    /* .
       .
       .
    */
HttpClient cli = new HttpClient();
string auth_request = "http://ws.audioscrobbler.com/2.0/?method=auth.getMobileSession&username=" + UsernameTBx.Text + "&authToken=" + lfm_authToken + "&api_key=" + lfm_api_key + "&api_sig=" + lfm_api_sig;

HttpResponseMessage auth = await cli.GetAsync(auth_request); //this works fine...

}

如果需要堆栈跟踪,请告诉我。

-Sagar

1 个答案:

答案 0 :(得分:2)

我想我想通了。我保留了其他人的帖子。

案例是Last.fm服务器不接受标题字段中的Expect:100Continue。所以我必须明确地将其改为false。

所以必须添加以下内容:

HttpClient cli = new HttpClient();
cli.DefaultRequestHeaders.ExpectContinue = false; 
相关问题