c# - Xamarin HTTP 请求超时

标签 c# http asynchronous xamarin.android

晚上好!

我试图清理/优化一些代码并最终发现了Xamarin HTTP 请求超时的问题(如我的原始线程中所述:Async Download and Deserialize)。

发现问题(仅使用 Xamarin.Android 进行测试;不了解 iOS):

当无法访问主机(例如,脱机的本地服务器)时,GetAsync 会在大约<< strong>3 分钟 并显示消息 Error: ConnectFailure (Connection timed out)。内部异常是 System.Net.Sockets.SocketsException(完整日志在这里:http://pastebin.com/MzHyp2FM)。

代码:

internal static class WebUtilities
{
    /// <summary>
    /// Downloads the page of the given url
    /// </summary>
    /// <param name="url">url to download the page from</param>
    /// <param name="cancellationToken">token to cancel the download</param>
    /// <returns>the page content or null when impossible</returns>
    internal static async Task<string> DownloadStringAsync(string url, CancellationToken cancellationToken)
    {
        try
        {
            // create Http Client and dispose of it even if exceptions are thrown (same as using finally statement)
            using (var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(5) })
            {
                // should I always do this?
                client.CancelPendingRequests();

                // Issue here; Timeout of roughly 3 minutes
                using (var response = await client.GetAsync(url, cancellationToken).ConfigureAwait(false))
                {
                    // if response was successful (otherwise return null)
                    if (response.IsSuccessStatusCode)
                    {
                        // return its content
                        return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    }
                }
            }
        }
        // TODO: split exceptions?
        catch (Exception ex) when (ex is System.Net.Sockets.SocketException ||
                                    ex is InvalidOperationException ||
                                    ex is OperationCanceledException ||
                                    ex is System.Net.Http.HttpRequestException)
        {
            WriteLine("DownloadStringAsync task has been cancelled.");
            WriteLine(ex.Message);
            return null;
        }

        // return null if response was unsuccessful
        return null;
    }
}

调用方式:

internal static async Task CallAsync(string url)
    {
        using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
        {
            var token = cts.Token;
            token.ThrowIfCancellationRequested();

            string result = await WebUtilities.DownloadStringAsync(url, token).ConfigureAwait(false);
        }
    }

设置 client.Timeout 似乎不起作用。

无论哪种方式,cancellationToken 不应该在 10 秒后自动取消吗?

此超时问题发生在:

  • 离线/无法访问的 IP 地址(在我的例子中是离线本地服务器 请求(例如 192.168.1.101:8080)(即使用 GetAsyncSendAsyncGetResponseAsync)

代码在以下情况下运行良好:

  • 请求来自桌面客户端(例如,WPF)。如果 IP 离线/无法访问,它非常快地抛出 4 个异常(无法建立连接,因为目标机器主动拒绝它)。

结论

Xamarin 似乎在 Http 请求中有一些错误(至少有超时?),因为它们没有给出预期的结果。根据我的阅读,它可能已经存在了几年(自 2012 年或 2013 年以来)。

Xamarin 单元测试也无济于事:https://github.com/xamarin/xamarin-android/blob/1b3a76c6874853049e89bbc113b22bc632ed5ca4/src/Mono.Android/Test/Xamarin.Android.Net/HttpClientIntegrationTests.cs

编辑

  • Timeout = TimeSpan.FromMilliseconds(1000) - 有效
  • Timeout = Timeout = TimeSpan.FromSeconds(1) - 不起作用 (?????)
  • Timeout = TimeSpan.FromMilliseconds(2000)(及以上)- 不 工作

有什么想法吗?谢谢!

最佳答案

我发现更改 Android 的 http 客户端设置解决了我的问题。
解决问题:

  • HttpClient实现到AndroidClientHandler
  • SSL/TLS 实现到 Native TLS 1.2+

在 Xamarin Android 项目选项中。 “默认”值使用的是导致问题的 Mono 自己的客户端。

我发布了更多细节 here .

关于c# - Xamarin HTTP 请求超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37382181/

相关文章:

c# - EntityFramework 延迟加载不起作用

c# - 如何使用 LINQ TakeWhile 和加入列表

delphi - HTTP 100 继续响应 可以有消息体吗?

javascript - Mocha 测试失败无法执行异步功能

c# - 在 LINQ 中转换 OrderBy Case 语句

通过 SSL 的 HTTP 基本身份验证

c# - 如何在 .Net/C# 中将日期转换为 HTTP 格式的日期

node.js - 无法访问 Mongoose 响应的对象属性

node.js - 我对 Node 中 'Non-blocking' 的理解是否正确?

c# - 多线程并行编程示例