繁体   English   中英

为什么在没有网络连接的情况下这个 webclient post code 没有超时?

[英]why is this webclient post code not being timed out when there is no network connection?

我的xamarin.ios应用程序中有这个 function,该应用程序将 object 发布到我的 Z8A5DA52ED1205721C. object 包含字符串和 1 个成员作为 base64 字符串。 当没有连接时,我似乎无法在不到 5 分钟的时间内获得超时并获得异常。 但是,当 object 中没有基数 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;
            }
        }

还有我的自定义网络客户端 class 所以我可以设置超时:

   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上运行良好,如果没有预期的互联网连接,它会超时。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM