我正在使用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