【问题标题】:why is this webclient post code not being timed out when there is no network connection?为什么在没有网络连接时这个 webclient post code 没有超时?
【发布时间】:2021-04-01 23:28:50
【问题描述】:

我的 xamarin.ios 应用程序中有这个函数,它可以将一个对象发布到我的 api 。该对象包含字符串和 1 个作为 base64 字符串的成员。当没有连接时,我似乎无法在不到 5 分钟的时间内获得超时并获得异常。但是,当对象中没有基数 64 时,它似乎正在超时。有什么想法可以让它发挥作用吗?这是我的代码:

public static string postData(object @params, string url)
        {
            MyWeWbClient webClient = new MyWeWbClient();

           
            try
            {
            
                webClient.Headers["content-type"] = "application/json";
                webClient.Headers.Add("Authorization", "Bearer " + Settings.GeneralSettings3);

                var reqString = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(@params, Formatting.Indented));
                byte[] resByte = webClient.UploadData(url, "post", reqString);
                var resString1 = Encoding.Default.GetString(resByte);
                webClient.Dispose();

                return resString1;
            }
            catch (WebException ex)
            {
                string responseText = "";

                var responseStream = ex.Response?.GetResponseStream();

                if (responseStream != null)
                {
                    using (var reader = new StreamReader(responseStream))
                    {
                        responseText = reader.ReadToEnd();

                    }
                }
                throw new Exception(responseText.ToString());
            }catch(Exception ex)
            {
                throw;
            }
        }

还有我的自定义 webclient 类,所以我可以设置超时:

   public  class MyWeWbClient : WebClient
    {
        protected override  WebRequest GetWebRequest(Uri uri)
        {
            WebRequest w = base.GetWebRequest(uri);
            w.Timeout = (int)TimeSpan.FromSeconds(10).TotalMilliseconds;//20 * 60 * 1000;
            return w;
        }
    }

提前致谢。任何帮助表示赞赏。

编辑:

相同的代码在 xamarin.android 上运行良好,如果没有预期的互联网连接,它会超时。

【问题讨论】:

标签: c# post xamarin.ios webclient


【解决方案1】:

我不推荐使用 webClient,我会使用像 restsharp 这样的外部依赖。

或者,您可以使用 Task.Run() 对其进行硬编码,但由于它在 Xamarin 中,我不能说。

【讨论】:

  • RestSharp 也给我同样的问题
猜你喜欢
  • 1970-01-01
  • 2012-07-30
  • 2017-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多