1

The following code for me is throwing an exception when I get a 400 error. Thus I'm never able to get return response as the exception is always caught.

using (var client = new HttpClient())
{
    try
    {
        var data = "...";

        var RequestBody = JsonConvert.SerializeObject(data);

        var requestUri = new Uri("url to error");
        var content = new StringContent(RequestBody, Encoding.UTF8, "application/json");

        var response = client.PostAsync(requestUri, content).Result;
        if (!response.IsSuccessStatusCode)  // it never gets in here since an exception is thrown
        {
            throw new HttpException(500, "PhantomJS status request failed");
        }
    }
    catch (Exception ex)
    {
        throw new Exception("PhantomJS status request failed", ex);
    }
}
TWilly
  • 4,863
  • 3
  • 43
  • 73
  • You are calling `client.PostAsynch(...)` but the title if your question refers to synchronous requests? Which is it? – Greg Burghardt Jan 20 '15 at 20:45
  • synchronous... I'm using code similar to what is recommended in this post. http://stackoverflow.com/questions/14435520/why-use-httpclient-for-synchronous-connection Adding .Result to the end of PostAsync causes the request to be synchronous. – TWilly Jan 20 '15 at 20:51
  • What is the class name of the exception? – Greg Burghardt Jan 20 '15 at 21:20
  • What is your question? What do you want to accomplish? – Christian Jan 20 '15 at 21:44
  • is the exception of type HttpRequestException ? – Dan Dinu Jan 20 '15 at 22:12
  • Turns out it was a problem not with httpclient but with the server I'm making a request to. It was not handling the keep-alive headers correctly. – TWilly Jan 20 '15 at 22:29

0 Answers0