Last active
December 20, 2015 02:19
-
-
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.
This file contains hidden or 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 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