Exception in HttpResponseMessage for async POST method in .NET4.5
I am developing a Windows 8 Application (Consumer Preview) in C #. It makes simple REST calls to the Last.fm API.
There is an exception that has bothered me for many days. I am trying to send a POST call to the Last.fm API method. But whenever I make a call, I get the following mssg -
"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.
If I print out the exception it says -
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)
My last.fm authentication API GET calls are working fine.
I add a piece of code:
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...
}
Please let me know if a stack trace is needed.
-Sagar
source to share
I think I figured it out. I am keeping a message so others can refer.
This is because Last.fm servers don't accept Expect: 100Continue in the header field. So I had to explicitly change it to false.
So I had to add the following:
HttpClient cli = new HttpClient();
cli.DefaultRequestHeaders.ExpectContinue = false;
source to share