0

I have found that if the Network Adapter is 'disabled' before the call is executed or there doesn't happen to be any networking available the HttpClient never times out or throws an exception.

Below you will find an example of my code.

private static async Task<string> ExecuteHttpMethod(HttpMethod httpMethod, string url, object item)
{
    string json = JsonConvert.SerializeObject(item);

    HttpContent httpContent = new StringContent(json, Encoding.UTF8, "application/json");

    var httpClient = new HttpClient();
    httpClient.Timeout = new TimeSpan(0, 0, 10);
    Task<HttpResponseMessage> responseTask = null;

    switch (httpMethod.Method)
    {
        case "GET":
        {
            responseTask = httpClient.GetAsync(url);
            break;
        }
        case "POST":
        {
            responseTask = httpClient.PostAsync(url, httpContent);
            break;
        }
        default:
        {
            throw new NotImplementedException(string.Format("{0} is not supported.", httpMethod.Method));
        }
    }

    try
    {
        responseTask.Result.EnsureSuccessStatusCode();

        string jsonResult = await responseTask.Result.Content.ReadAsStringAsync();

        return jsonResult;
    }
    catch (Exception ex)
    {
        Debug.Write(ex.ToString());
        return string.Empty;
    }
}

Update 1 using await:

HttpContent httpContent = new StringContent(json, Encoding.UTF8, "application/json");

var httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 0, 10);
HttpResponseMessage responseTask = null;

switch (httpMethod.Method)
{
    case "GET":
    {
        responseTask =  await httpClient.GetAsync(url);
        break;
    }
    case "POST":
    {
        responseTask = await httpClient.PostAsync(url, httpContent);
        break;
    }
    default:
    {
        throw new NotImplementedException(string.Format("{0} is not supported.", httpMethod.Method));
    }
}

try
{
    responseTask.EnsureSuccessStatusCode();

    string jsonResult = await responseTask.Content.ReadAsStringAsync();


    return jsonResult;
}
catch (Exception ex)
{
    Debug.Write(ex.ToString());
    return string.Empty;
}
Mr. Young
  • 2,364
  • 3
  • 25
  • 41

0 Answers0