Internal Server Error when doing a POST with HttpClient in Windows Phone 8
X

6

6

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?

Xenogenesis answered 7/9, 2013 at 13:38 Comment(0)
P
2

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.

Periscope answered 7/9, 2013 at 17:28 Comment(3)
That may be my problem. How do I set the media type to "application/x-www-form-urlencoded"?Xenogenesis
@NiiLaryea set stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");Periscope
how do i find out what media type the server is expecting?Lentissimo
B
5

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.

Besiege answered 7/9, 2013 at 18:28 Comment(0)
P
5

If anyone is getting 500 (internal server error) when sending data with everything correct, using .net Standard, make sure ExpectContinue is set to false. Some APIs did not accept header Expect: 100-continue and send a 500 (internal server error) as response.

I lost a day because of this. I had to use Mockoon to see environment logs and what was being sent.

private TItemType AddItem<TItemType>(TItemType item)
{
    try
    {
        HttpClient httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.ExpectContinue = false; // <-- Make sure it is false.
        httpClient.Timeout = TimeSpan.FromSeconds(60);
        httpClient.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
                        
        var uri = new Uri("https://your.url/your/api");
        var content = new System.Net.Http.StringContent(
            JsonConvert.SerializeObject(item), Encoding.UTF8, "application/json");

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);
        request.Content = content;

        HttpResponseMessage response = HttpClient.SendAsync(request).Result;
        if (response.StatusCode == HttpStatusCode.Created)
        {
            string responseContent = response.Content.ReadAsStringAsync().Result;
            return JsonConvert.DeserializeObject<TItemType>(responseContent);
        }

        return default;
    }
    catch (Exception)
    {
        throw;
    }
}
Preposterous answered 30/7, 2021 at 12:57 Comment(0)
P
2

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.

Periscope answered 7/9, 2013 at 17:28 Comment(3)
That may be my problem. How do I set the media type to "application/x-www-form-urlencoded"?Xenogenesis
@NiiLaryea set stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");Periscope
how do i find out what media type the server is expecting?Lentissimo
G
1

HTTP code 500 means that this is an error on your server. In plain words, the server threw an exception when trying to process this POST request.

So, this error has nothing to do with HttpClient or with your WP8 app.

Debug your server first and see what causes the exception, and if you're having problems there post another question.

Gaulin answered 7/9, 2013 at 14:34 Comment(2)
However, there were no such errors when I tried with HttpWebRequest.Xenogenesis
It would be hard to tell what the problem that may result due to differences between HttpWebRequest and HttpClient. I would try to debug the server and see if there is any difference in the received HTTP POST request.Gaulin
D
1

I know it's been a while but I've stumbled upon this question looking for a way to send a POST request with a application/x-www-form-urlencoded content type.

Microsoft.Net.Http, as of version 2.2.28, includes the FormUrlEncodedContentclass which allows you to send such a request.

A code sample would look like this:

var client = new HttpClient();
var data = new Dictionary<String, String>
{
    { "firstname", "taj" },
    { "lastname", "burrow" }
};

var response = await client.PostAsync("http://mygreatapi.com", data);

For the curious ones, the constructor of FormUrlEncodedContent takes an IEnumerable<KeyValuePair<String, String>>

Dianthus answered 9/9, 2014 at 16:1 Comment(0)
O
0

my program is ASP.NET WEB API2 running on dotNetFramwork4.8.1

I getting 500 (internal server error) even sending data with correct.

Setting ExpectContinue to False solved my problem!

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

Or you can set the global ExpectContinue to false

ServicePointManager.Expect100Continue = false;

Finally thanks for this reply which helped me https://mcmap.net/q/1640617/-internal-server-error-when-doing-a-post-with-httpclient-in-windows-phone-8

Ocampo answered 5/3 at 13:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.