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;
}
}
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.
try below code in request
request.Headers.Add("If-Modified-Since", DateTime.Now.ToString());
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With