Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient response not get refresh

I am using HttpClient to communicate with web service for send/receive (response in JSON format). But I am facing some issue while receiving data. I am calling web service every 5 min to refresh the content at my windows phone using HttpClient but the response coming same again and again. For getting new response I need to exit from application and call service again. Is HttpClient need some refresh or clear data process? Do I need to implement some other approch to get new refreshed result every time? Please suggest. Below is my implementation

public async Task<string> GetMyData(string urlToCall)
    {
        try
        {
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.Timeout = TimeSpan.FromMilliseconds(double.Parse(30000));
                HttpRequestMessage request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, urlToCall);
                var response = await httpClient.SendAsync(request);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var responseString = await response.Content.ReadAsStringAsync();
                    return responseString;
                }
                else
                {
                    return string.Empty;
                }                    
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("Exception => RestfulWebService =>GetMyData: " + ex.Message);
            return string.Empty;
        }
    }
like image 574
gofor.net Avatar asked Jul 08 '14 07:07

gofor.net


2 Answers

Windows Phone (unlike Windows Store Apps) has an optimization to reduce the number of calls to the server.

So by default SendAsync for a get request(Or GetAsync) in Phone is implemented in such a way that if you are making the same get request call again, it will not even hit the server but will directly return the previous result it fetched for you.

If you want to manually override this optimization, you have manually add the header "IfModifiedSince" to the request and set the datetimeoffset to now. This will make the client call the server again each time.

Here's the code

      HttpRequestMessage request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, urlToCall);
      request.Headers.IfModifiedSince = new DateTimeOffset(DateTime.Now);
      var response = await httpClient.SendAsync(request);

Notice that I have added one line in the middle of your code, after creating your request and before sending it to the server.

Hope it helps.

like image 66
yifan Avatar answered Oct 13 '22 20:10

yifan


try below code in request

request.Headers.Add("If-Modified-Since", DateTime.Now.ToString());

.

like image 20
Muhammad Saifullah Avatar answered Oct 13 '22 19:10

Muhammad Saifullah