HttpClient exception in Windows 8 app

2019-09-05 21:11发布

问题:

I am using HttpClient to send and receive data from the server in my Windows 8 app.

Below is my code:

HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
handler.AutomaticDecompression = DecompressionMethods.GZip;

HttpClient httpClient = new HttpClient(handler);
httpClient.Timeout = TimeSpan.FromSeconds(30);
httpClient.DefaultRequestHeaders.ExpectContinue = false;

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, URL);

request.Content = new StreamContent(new System.IO.MemoryStream(_postDataInBytes));
request.Content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

HttpResponseMessage response = await httpClient.SendAsync(request);

Now the problem is that I get an exception at SendAsync() function. The exception is "The underlying connection was closed: An unexpected error occurred on a receive". This occurs randomly. Can anybody please tell me what is the problem here?