[英]C# HttpClient weird error
I have the following code which runs with no issues on Windows Phone 8, but running on Windows 8 results in error. 我有以下代码,该代码在Windows Phone 8上运行没有问题,但是在Windows 8上运行会导致错误。
Error: 错误:
Exception received while submitting the payload: at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at FooProject.HTTPHelper.<SubmitRequestToMobileAnalytics>d__a.MoveNext() in c:\Users\foo_000\Documents\GitHub\FooProject\HttpHelper.cs:line 135
Inner Exception is: at System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean aborting)
at System.Net.ConnectStream.System.Net.ICloseEx.CloseEx(CloseExState closeState)
at System.Net.ConnectStream.Dispose(Boolean disposing)
at System.IO.Stream.Close()
at System.Net.Http.HttpClientHandler.<>c__DisplayClass8.<GetRequestStreamCallback>b__6(Task task)
Code: 码:
string jsonPayload = "<<<Some JSON Payload>>>";
using (HttpClient httpClient = new HttpClient())
{
try
{
//Converting the JSON payload as GZipped byte array
byte[] payload = CompressAsByte(jsonPayload);
if (payload != null)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, Config.Instance().TrackingServer);
request.Content = new ByteArrayContent(payload);
request.Content.Headers.Add("Content-Encoding", "gzip");
request.Content.Headers.Add("Content-Type", "application/json");
HttpResponseMessage response = await httpClient.SendAsync(request);
return (int)response.StatusCode;
}
else
{
return 0;
}
}
catch (System.Exception e)
{
Logger.Log("Exception received while submitting the payload: " + e.StackTrace);
if (e.InnerException != null)
{
Logger.Log("Inner Exception is: " + e.InnerException.StackTrace);
}
return 0;
}
}
For Windows Phone 8 App, I am referencing Microsoft HttpClient from the NuGet repository. 对于Windows Phone 8 App,我从NuGet存储库引用Microsoft HttpClient。 For Windows 8, already the packages System.Net and System.Net.Http are visible to me. 对于Windows 8,我已经可以看到软件包System.Net和System.Net.Http。
For some reason, the same code running on Phone works and on Windows 8 Tablet (simulator), it throws error. 由于某些原因,在Phone上运行的相同代码和在Windows 8 Tablet(模拟器)上运行的相同代码会引发错误。
Am I missing anything using HttpClient on Windows 8? 我在Windows 8上使用HttpClient是否缺少任何内容?
I added the following code, it worked like magic. 我添加了以下代码,它像魔术一样工作。
request.Content.Headers.Add("Content-Length", payload.Length.ToString());
I don't know why it succeeded without this line on Windows Phone 8. 我不知道为什么在Windows Phone 8上没有此行便成功了。
But it worked. 但这行得通。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.