Pergunta

The following code gets stuck in a while loop when an exception is encountered. This is because GetResponse is caching the data.

According to fiddler, no data after the first request is issued.

Is it a best practice to recreate the webclient to solve the "refresh" issue I'm having?

    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;
    }
Foi útil?

Solução

No. HttpWebRequests are not reusable.

Just move the creation of your WebRequest into the body of your loop:

    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;
                    //...
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top