我目前正在使用内部 API 和 visual studio(对它们都是新手)。我正在尝试向服务器提交一个 GET 请求,它会给我一个包含用户信息的 JSON。预期的 JSON 响应中的字段之一是 connect_status,如果它正在连接则显示 true,一旦连接完成则显示 false,这意味着已收到响应。到目前为止,我一直在使用 Sleep 进行以下操作,等待一段时间直到得到响应。
bool isConnected;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost");
request.Method = WebRequestMethods.Http.Get;
request.ContentType = "application/json";
System.Threading.Thread.Sleep(10000);
do
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader info = new StreamReader(receiveStream);
string json = info.ReadToEnd();
accountInfo user1 = JsonConvert.DeserializeObject<accountInfo>(json);
Console.WriteLine(jsonResponse);
isConnected = user1.connect_status;
}
while (isConnected == true);
问题是我必须等待更长的时间,所花费的时间是可变的,这就是为什么我必须设置更长的 sleep 时间。 Alsosomeimtes 10 秒可能还不够,在这种情况下,当 do while 循环第二次循环时,我在 while(isConnected==true) 处出现异常说
NUllReferenceException was unhandled. Object reference not set to an instance of an object.
有什么更好/不同的方法可以做到这一点,因为我认为我的做法不对。
最佳答案
这里有一个选项,如果使用 .NET 4.5:
HttpMessageHandler handler = new HttpClientHandler { CookieContainer = yourCookieContainer };
HttpClient client = new HttpClient(handler) {
BaseAddress = new Uri("http://localhost")
};
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpContent content = new StringContent("dataForTheServerIfAny");
HttpResponseMessage response = await client.GetAsync("relativeActionUri", content);
string json = await response.Content.ReadAsStringAsync();
accountInfo user1 = JsonConvert.DeserializeObject<accountInfo>(json);
这样您就可以让 .NET 为您处理等待等事情。
关于c# - 如何等待服务器成功响应 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17734494/