【问题标题】:Xamarin.Forms - unhandled exception at HttpClient SendAsyncXamarin.Forms - HttpClient SendAsync 处未处理的异常
【发布时间】:2015-07-16 00:36:56
【问题描述】:

尝试在 Android 上发送 HTTP 请求时遇到异常。 在 WinPhone 上,它可以工作。 这是我的代码:

        string resp = null;

        using (var client = new HttpClient())
        {
            var httpRequest = new HttpRequestMessage(new HttpMethod("POST"), _uri);
            //client.BaseAddress = new Uri(_uri);
            try
            {
                client.Timeout = TimeSpan.FromSeconds(30);
                var _cancelTokenSource = new CancellationTokenSource();
                var _cancelToken = _cancelTokenSource.Token;
                var response = await client.SendAsync(httpRequest, _cancelToken);
                resp = await response.Content.ReadAsStringAsync();
                //var result = await client.PostAsync("", new StringContent(json.ToString(), Encoding.UTF8, "application/json"));
                //resp = await result.Content.ReadAsStringAsync();
            }
            catch (Exception e)
            {
                Debug.WriteLine("HTTP ERROR: " + e.Message);
                throw e;
            }
        }

On Properties > Android Manifest 我已经检查了 INTERNET 以获得许可。 此外,它经历了一个未处理的异常,我看不到发生了什么。它没有显示确切的错误,也没有显示我设置的未处理异常的方法:

AndroidEnvironment.UnhandledExceptionRaiser += AppDroid_UnhandledExceptionHandler;

知道什么是错误的,或者知道如何查看错误信息吗?在 WinPhone 上,当出现一些意外错误时,它会到达我的方法,然后很容易修复。

谢谢!

【问题讨论】:

  • 同样的问题,你找到解决办法了吗?

标签: c# android xamarin.forms


【解决方案1】:

Android HttpClient 存在一个已知错误。看到这个:http://forums.xamarin.com/discussion/36470/httpclient-postasync-deadlock-system-net-sockets-connect-internal

改成:

using (var client = new HttpClient())
        {
            var httpRequest = new HttpRequestMessage(new HttpMethod("POST"), _uri);
            //client.BaseAddress = new Uri(_uri);
            try
            {
                client.Timeout = TimeSpan.FromSeconds(30);
                var _cancelTokenSource = new CancellationTokenSource();
                var _cancelToken = _cancelTokenSource.Token;
                var response = await client.SendAsync(httpRequest, _cancelToken).ConfigureAwait(false);
                resp = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            }
            catch (Exception e)
            {
                Debug.WriteLine("HTTP ERROR: " + e.Message);
                throw e;
            }
        }

你也可以试试 ModernHttpClient。它是直接替换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 2011-11-19
    • 2019-07-18
    • 1970-01-01
    相关资源
    最近更新 更多