I am posting a string to a web server this way:
private async Task makeRequest(string url, string postData)
{
HttpClient client = null;
HttpResponseMessage response = null;
try
{
client = new HttpClient();
response = await client.PostAsync(url, new StringContent(postData));
response.EnsureSuccessStatusCode();
Debug.WriteLine(response.StatusCode + " " + response.ReasonPhrase);
}
catch (HttpRequestException e)
{
Debug.WriteLine(e.Message);
}
}
But response.EnsureSuccessStatusCode();
throws a HttpRequestException
. When I did a e.Message
on the exception, it says : Response status code does not indicate success: 500 (Internal Server Error).
.
What am I doing wrong that I get that error? And how do I correct it?
The HyperText Transfer Protocol (HTTP) 500 Internal Server Error server error response code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request. This error response is a generic "catch-all" response.
SendAsync(HttpRequestMessage, HttpCompletionOption, CancellationToken) Send an HTTP request as an asynchronous operation. SendAsync(HttpRequestMessage) Send an HTTP request as an asynchronous operation.
PostAsync(String, HttpContent) Send a POST request to the specified Uri as an asynchronous operation. PostAsync(Uri, HttpContent) Send a POST request to the specified Uri as an asynchronous operation.
Your best solution here, as a wise man said, in HTTP there is not magic.
Download Fiddler2, setup a proxy on the emulator to connect to it. Then run your code with HttpWebRequest
save the header somewhere and then run it again with HttpClient
.
Compare the two files carefully and fix whats needs to be fixed. Please note that even the smallest difference might matter.
POSTing a StringContent will set the content type to text/plain
. You might find the server doesn't like that. Try to find out what media type the server is expecting and set the Headers.ContentType
of the StringContent
instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With