0

我有以下代码在 Windows Phone 8 上运行没有问题,但在 Windows 8 上运行会导致错误。

错误:

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)

代码:

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;

                }
            }

对于 Windows Phone 8 应用程序,我从 NuGet 存储库引用 Microsoft HttpClient。对于 Windows 8,我已经可以看到 System.Net 和 System.Net.Http 包。

出于某种原因,在 Phone 上运行的相同代码可以在 Windows 8 平板电脑(模拟器)上运行,它会引发错误。

我在 Windows 8 上使用 HttpClient 是否遗漏了什么?

4

1 回答 1

0

我添加了以下代码,它就像魔术一样工作。

request.Content.Headers.Add("Content-Length", payload.Length.ToString());

我不知道为什么它在 Windows Phone 8 上没有这条线就成功了。

但它奏效了。

于 2013-09-04T04:26:57.710 回答