【问题标题】:Exception in HttpResponseMessage for async POST method in .NET4.5.NET4.5 中异步 POST 方法的 HttpResponseMessage 异常
【发布时间】:2012-04-18 15:58:35
【问题描述】:

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

这个异常困扰了我很多天。我正在尝试向 Last.fm API 方法发送 POST 调用。但是每当我拨打电话时,我都会收到以下消息 -

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

如果我打印出它所说的异常 -

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

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

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

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

我附上代码sn-p:

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...

}

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

-萨加尔

【问题讨论】:

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


    【解决方案1】:

    我想我想通了。我保留这个帖子供其他人参考。

    情况是 Last.fm 服务器不接受 header 字段中的 Expect:100Continue。所以我不得不明确地将其更改为 false。

    所以必须添加以下内容:

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

    【讨论】:

    • 谢谢!!几天来我一直在努力解决这个问题,但我在任何地方都找不到解决方案。你拯救了我的一天。
    猜你喜欢
    • 2017-08-05
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 2018-12-31
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    相关资源
    最近更新 更多