2

当遇到异常时,以下代码会卡在 while 循环中。这是因为 GetResponse 正在缓存数据。

根据fiddler的说法,第一次请求发出后没有数据。

重新创建网络客户端以解决我遇到的“刷新”问题是最佳实践吗?

    private static ReportStatusEnum GetReportStatus(string domain, string oAuthKey, long permissionReportID)
    {
        string target = string.Format("https://{0}.egnyte.com/pubapi/v1/audit/jobs/{1}", domain, permissionReportID);

        var client = new WebClient();

         string result ="";
        var request = (HttpWebRequest)WebRequest.Create(target);
        request.ContentType = "application/json";
        request.Headers.Add("Authorization", "Bearer " + oAuthKey);
        request.AllowAutoRedirect = false;

        bool callComplete = false;
        while (callComplete != true)
        {
            try
            {
                using (var response = request.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        result = reader.ReadToEnd();
                    }
                }

                JToken result2 = JObject.Parse(result);
                var statusResult = result2.SelectToken("status");

                ReportStatusEnum ret = ReportStatusEnum.error;

                Enum.TryParse<ReportStatusEnum>(statusResult.ToString(), out ret);

                Console.WriteLine("The returned variable is:" + ret);

                callComplete = true;
                return ret;
            }
            catch (System.Net.WebException e)
            {
                if (e.Response != null)
                    if (e.Response.ContentLength > 0)
                    {
                        if (e.Response.Headers["X-Mashery-Error-Code"] == "ERR_403_DEVELOPER_OVER_QPS")
                        {
                            Thread.Sleep(60000); Console.Write("*QPS HIT*");
                        }
                    }
            }
        }
        return ReportStatusEnum.error;
    }
4

1 回答 1

1

不可以。HttpWebRequests 不可重用。

只需将 WebRequest 的创建移动到循环体中:

    string result ="";

    bool callComplete = false;
    while (callComplete != true)
    {
        var request = (HttpWebRequest)WebRequest.Create(target);
        request.ContentType = "application/json";
        request.Headers.Add("Authorization", "Bearer " + oAuthKey);
        request.AllowAutoRedirect = false;
                    //...
于 2013-11-08T16:46:43.470 回答