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

3

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

有一个异常困扰了我很多天。我试图向Last.fm API方法发送POST调用。但每次我发送一个调用,都会收到以下消息:

"An exception of type 'System.Net.Http.HttpRequestException' occurred in mscorlib.dll but was not handled in user code". Additional information: An error occurred while sending the request.

如果我打印出异常,它会说 -

System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly.

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

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

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

这里附上代码片段:

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个回答

2

我想我弄清楚了。我会保留这篇文章供他人参考。

问题在于Last.fm服务器不接受头部字段中的Expect: 100 Continue。因此,我必须明确将其更改为false。

所以我不得不添加以下内容:

HttpClient cli = new HttpClient();
cli.DefaultRequestHeaders.ExpectContinue = false; 

谢谢!我已经为解决这个问题苦苦挣扎了好几天,但是我无法在任何地方找到解决方案。你救了我的一天。 - Stefano Driussi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接