3

我正在用 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 调用工作正常。

我附上一个代码片段:

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

}

请让我知道是否需要堆栈跟踪。

-萨加尔

4

1 回答 1

2

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

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

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

HttpClient cli = new HttpClient();
cli.DefaultRequestHeaders.ExpectContinue = false; 
于 2012-04-06T09:00:39.477 回答