簡體   English   中英

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

[英]Exception in HttpResponseMessage for async POST method in .NET4.5

我正在為 C# 中的 Windows 8(消費者預覽版)開發一個應用程序。它對 Last.fm API 進行簡單的 REST 調用。

有一個例外困擾了我很多天。 我正在嘗試將 POST 調用發送到 Last.fm API 方法。 但是每當我打電話時,我都會收到以下消息 -

“‘System.Net.Http.HttpRequestException’類型的異常發生在 mscorlib.dll 中,但未在用戶代碼中處理”。 附加信息:發送請求時出錯。

如果我打印出它說的異常 -

System.Net.Http.HttpRequestException:發送請求時出錯。 ---> System.Net.WebException:基礎連接已關閉:連接意外關閉。

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

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

}

請讓我知道是否需要堆棧跟蹤。

-薩加爾

我想我明白了。 我保留該職位以供其他人參考。

情況是 Last.fm 服務器不接受 header 字段中的 Expect:100Continue。 所以我不得不明確地將其更改為 false。

所以不得不添加以下內容:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM