Reputation: 1289
With httpClient
I do a POST request, however, the problem is that even if there
is no connection because the destination API is down, it does not return any errors.
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(proxySettingsConfiguration.BaseAdress);
var json = JsonConvert.SerializeObject(item);
var parameters = new Dictionary<string, string> { { "Application", "Demo" }, { "Payload", json } };
var encodedContent = new FormUrlEncodedContent(parameters);
var response = await httpClient.PostAsync(proxySettingsConfiguration.RequestUri, encodedContent);
}
Is there a way to check beforehand if the destination works? Without using PING
Upvotes: 1
Views: 9629
Reputation: 69
Recently I used Youtube API, and I had the same problems with getting the data, searching the song name...etc, what I did is I put the (in your case)
response = await httpClient.PostAsync(proxySettingsConfiguration.RequestUri, encodedContent);
in try/catch, so it would be
try
{
response = await httpClient.PostAsync(proxySettingsConfiguration.RequestUri, encodedContent);
}
catch (Exception ex)
{//In my case I was looking at this error
if (ex.GetType().ToString() == "Google.Apis.Auth.OAuth2.Responses.TokenResponseException")
{
MessageBox.Show("Failed to login", "Error on login",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Failed to login", "Error on login",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
If you print out the Exception(messagebox,debug) you will see it's a type of error,or you can search more information about the API you are using, and see what error types can it throw,find the one that's good,you can add multiple ones with different messages,so your program will not crash if it has some kind of errors. Hope it helps a little bit.
Upvotes: 1