Skip to content

Instantly share code, notes, and snippets.

@Ryanb58
Last active December 20, 2015 02:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ryanb58/6055088 to your computer and use it in GitHub Desktop.
Save Ryanb58/6055088 to your computer and use it in GitHub Desktop.
Code to connect to API via HttpWebRequest API and get the JSON results returned into a dynamic object... JSON.net req.
public void LoadData(Uri uri)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request);
}
private void ReadWebRequestCallback(IAsyncResult callbackResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string limitHeader = response.Headers["X-RateLimit-Remaining"];
string results = reader.ReadToEnd();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
//Read the JSON from the string.
JsonTextReader jsonReader = new JsonTextReader(new StringReader(results));
//Create instance of Json serializer.
JsonSerializer se = new JsonSerializer();
//Deserialize the text and place in dynamic type, for easy manipulation.
dynamic parsedData = se.Deserialize(jsonReader);
int i = 0;
foreach (var item in parsedData)
{
this.Items.Add(new ItemViewModel()
{
ID = i.ToString(),
limitHeader = limitHeader
});
i++;
}
});
}
}
catch (Exception e)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Network error occured " + e.Message);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment