gpt4 book ai didi

c# - 如何重新发出网络请求?我必须重新创建 Webclient 吗?

转载 作者:太空宇宙 更新时间:2023-11-03 13:32:57 25 4
gpt4 key购买 nike

当遇到异常时,以下代码会陷入 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;
}

最佳答案

没有。 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;
//...

关于c# - 如何重新发出网络请求?我必须重新创建 Webclient 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19863944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com