Created
February 7, 2014 16:46
-
-
Save CodisRedding/8866605 to your computer and use it in GitHub Desktop.
HttpGetAsync using query pagination
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public async Task<IList<T>> HttpGetAsync<T>(string urlSuffix, string nodeName) | |
{ | |
string next = null; | |
string response = null; | |
var records = new List<T>(); | |
var url = Common.FormatUrl(urlSuffix, _instanceUrl, _apiVersion); | |
try | |
{ | |
do | |
{ | |
if (next != null) | |
url = Common.FormatUrl(string.Format("query/{0}", next.Split('/').Last()), _instanceUrl, _apiVersion); | |
var request = new HttpRequestMessage | |
{ | |
RequestUri = new Uri(url), | |
Method = HttpMethod.Get | |
}; | |
request.Headers.Add("Authorization", "Bearer " + _accessToken); | |
var responseMessage = await _httpClient.SendAsync(request); | |
response = await responseMessage.Content.ReadAsStringAsync(); | |
if (responseMessage.IsSuccessStatusCode) | |
{ | |
var jObject = JObject.Parse(response); | |
var jToken = jObject.GetValue(nodeName); | |
next = (jObject.GetValue("nextRecordsUrl") != null) ? jObject.GetValue("nextRecordsUrl").ToString() : null; | |
records.AddRange(JsonConvert.DeserializeObject<IList<T>>(jToken.ToString())); | |
} | |
} while (!string.IsNullOrEmpty(next)); | |
return (IList<T>)records; | |
} | |
catch (Exception) | |
{ | |
var errorResponse = JsonConvert.DeserializeObject<ErrorResponses>(response); | |
throw new ForceException(errorResponse[0].errorCode, errorResponse[0].message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment