简体   繁体   中英

How to wait for a server to successfully respond to an HTTP request

I am currently working with an internal API and visual studio (new to both of them). I am trying to submit a GET request to the server which will give me a JSON with the user info. One of the field in the expected JSON response is connect_status which shows true if its connecting and false once the connection is done meaning the response has been received. So far I have been working with the following using Sleep to wait for a bit until getting the response.

    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);

The problem with this is that I have to wait for a longer time, the time it takes is variable and that's why I have to set a higher sleep time. Alsosomeimtes 10 seconds might not be enough and in that case when the do while loop loops the second time I get an exception at while(isConnected==true) saying

NUllReferenceException was unhandled. Object reference not set to an instance of an object.

What would be a better/different way of doing this as I don't think the way I am doing is right.

One option here, if using .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);

This way you let .NET take care of that waiting and such for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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