How to call a REST API from a Windows Service
<p>I am trying to call a Rest API from a windows service.  I have never attempted this before.  I am not sure why I am not able to make this call.</p>

<p>My code:</p>

<pre><code>    string urlParameter = "posts/1";
    var client = new HttpClient();
    client.BaseAddress = new Uri("http://jsonplaceholder.typicode.com/");
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    HttpResponseMessage response = client.GetAsync(urlParameter).Result;
    if (response.IsSuccessStatusCode)
    {
        var dataObj = response.Content.ReadAsAsync&lt;IEnumerable&lt;MyType&gt;&gt;().Result;
    }
</code></pre>

<p>I am getting the following error:</p>

<ul>
<li><p>Message: An error occurred while sending the request.</p></li>
<li><p>Inner Exception Message: {"The underlying connection was closed: The
connection was closed unexpectedly."}</p></li>
<li><p>Inner Exception Stack Trace    at
System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)<br>
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult
ar)</p></li>
</ul>

<p>This error is being generated on the following line:</p>

<pre><code>HttpResponseMessage response = client.GetAsync(urlParameter).Result;
</code></pre>

<p>Any suggestions would be appreciated.</p>

<p>EDIT: (Updated Code)</p>

<pre><code>    string urlParameter = "posts/1";
    var client = new HttpClient();
    client.BaseAddress = new Uri("http://jsonplaceholder.typicode.com/");
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    try
    {
        //var response = await client.GetAsync(urlParameter);
        var task = client.GetAsync(urlParameter);
        task.Wait();
        var response = task.Result;

        if (response.IsSuccessStatusCode)
        {
            var dataObj = response.Content.ReadAsAsync&lt;IEnumerable&lt;MyType&gt;&gt;().Result;
        }
    }
    catch (Exception ex)
    {
        string a = ex.Message;
        string b = ex.ToString();
    }
</code></pre>

<p>EDIT 2: (Still getting the same error)</p>

<pre><code>private static async void TestAPI2()
{
    using (HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.Add("Get", "application/json");

        var response = await client.GetAsync("http://jsonplaceholder.typicode.com/posts/1");

        string context = await response.Content.ReadAsStringAsync();

    }
}
</code></pre>