I am learning C# and want to use the Riot API. I just want to receive that:
{
"type":"champion",
"version":"6.1.1",
"data":{
"Thresh":{
"id":412,
"key":"Thresh",
"name":"Thresh",
"title":"the Chain Warden"
},
"Aatrox":{
"id":266,
"key":"Aatrox",
"name":"Aatrox",
"title":"the Darkin Blade"
},...
I found this here: Deserialize JSON from Riot API C#
Can someone help me? I have no Idea what to do.
sincerly
MasterR8
PS: I already googled 3 hours...
If you want to get the json string try this, this take a URL and tries to do the request and returns the response. You can find the url in the sandbox mode provided on the riot API site.
using System.Net;
using System.IO;
public string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
}
throw;
}
}
This is the easy part :) mapping the response to a POCO is what annoys me the most. If anybody reads this and has a good solution plzz link me.
Related
I'm developing a small app that pulls issues from JIRA from a given list of issue ids, however some of them don't exist and the API call returns a 400 Bad Request message.
This is the relevant block of code I have so far (C#):
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(thejiraurl);
request.Method = "GET";
request.ContentType = "Content-Type: application/json";
request.Accept = "application/json";
string mergedCredentials = "thecredentials :)";
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
string encodedCredentials = Convert.ToBase64String(byteCredentials);
request.Headers.Add("Authorization", "Basic " + encodedCredentials);
try
{
WebResponse response = request.GetResponse(); //this line breaks because some records don't exist anymore, that's ok, but at least I need to know which ones! those are found in the response that I can't see here but I can with Fiddler! #.#
Stream data = response.GetResponseStream();
}
catch(WebException ex)
{
Console.WriteLine(ex.Message);
if(ex.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)ex.Response).StatusCode); //This is 'BadRequest'
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)ex.Response).StatusDescription); //This is 'Bad Request'
using (Stream responseStream = ex.Response.GetResponseStream())
using (StreamReader responseReader = new StreamReader(responseStream))
{
string responseMessage = responseReader.ReadToEnd(); //This is a long message but do not has the errormessages seen with Fiddler (and even in a internet browser)
Console.WriteLine(responseMessage);
}
}
}
However when I use Fiddler I can see the actual errormessages returned, that looks like:
{"errorMessages":["A value with ID '1' does not exist for the field 'key'."],"errors":{}}
How can I get this messages using C# or vb?
This is very similar to question, but that one is with Java: https://answers.atlassian.com/questions/147793/retrieving-errormessages-when-a-call-to-the-rest-api-fails-using-httpurlconnection
I appreciate any help.
I'm currently working on getting course offerings from org unit id using c#.
I'm brand-new to D2L valence. I have app ID/key pair and user ID/Key pair.
I am going to enter org unit id, get json response, parse the json response in c#, and output the associated course code and name.
string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
this is my GET code. And, I'm trying to call it. The url and the main code are the following:
string url = "http://test.ca/d2l/api/lp/1.0/courses/644849";
GET(url);
The problem is I'm getting error says: The remote server returned an error: (403)Forbidden.
Also, I've tried this url:
string url = "http://lms.valence.desire2learn.com/d2l/api/lp/1.0/courses/644849";
This time, I got this error (Object reference not set to an instance of an object.)
I have app id/key pair and user id/key pair.
What should I do to solve this problem and end up with getting course offerings.
Thanks in advance, Phillip
The reason you're getting a 403 forbidden is because you are not sending the appropriate identifiers and signatures on your query string to allow your request to be authenticated (see http://docs.valence.desire2learn.com/basic/auth.html#id4).
If you are using C#, I'd recommend using the Valence SDK located on Nuget to generate appropriate URLs. Take a look at https://github.com/Brightspace/valence-sdk-dotnet/tree/master/samples/Basic for a sample project using the SDK, specifically, https://github.com/Brightspace/valence-sdk-dotnet/blob/master/samples/Basic/Basic/Controllers/HomeController.cs, shows how you can use the SDK methods to make a whoami request.
I am hosting a web service in ASP.Net MVC3 which returns a Json string. What is the best way to call the webservice from a c# console application, and parse the return into a .NET object?
Should I reference MVC3 in my console app?
Json.Net has some nice methods for serializing and deserializing .NET objects, but I don't see that it has ways for POSTing and GETing values from a webservice.
Or should I just create my own helper method for POSTing and GETing to the web service? How would I serialize my .net object to key value pairs?
I use HttpWebRequest to GET from the web service, which returns me a JSON string. It looks something like this for a GET:
// Returns JSON string
string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try {
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream()) {
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex) {
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
I then use JSON.Net to dynamically parse the string.
Alternatively, you can generate the C# class statically from sample JSON output using this codeplex tool: http://jsonclassgenerator.codeplex.com/
POST looks like this:
// POST a JSON string
void POST(string url, string jsonContent)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
using (Stream dataStream = request.GetRequestStream()) {
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try {
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
length = response.ContentLength;
}
}
catch (WebException ex) {
// Log exception and throw as for GET example above
}
}
I use code like this in automated tests of our web service.
WebClient to fetch the contents from the remote url and JavaScriptSerializer or Json.NET to deserialize the JSON into a .NET object. For example you define a model class which will reflect the JSON structure and then:
using (var client = new WebClient())
{
var json = client.DownloadString("http://example.com/json");
var serializer = new JavaScriptSerializer();
SomeModel model = serializer.Deserialize<SomeModel>(json);
// TODO: do something with the model
}
There are also some REST client frameworks you may checkout such as RestSharp.
Although the existing answers are valid approaches , they are antiquated . HttpClient is a modern interface for working with RESTful web services . Check the examples section of the page in the link , it has a very straightforward use case for an asynchronous HTTP GET .
using (var client = new System.Net.Http.HttpClient())
{
return await client.GetStringAsync("https://reqres.in/api/users/3"); //uri
}
I'm pretty RESTless right now because I keep getting incomplete responses from Amazon. I'm using the Product Advertising API, making one ItemLookup request to the server.
The C# code is pretty basic:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
string resultString;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
resultString = sr.ReadToEnd();
}
The number of chars I recieve is 17408- pretty constant but I've seen something around 16k as well.
This is how it always ends:
...ount><CurrencyCode>EUR</CurrencyCode><FormattedPrice>EUR 11,33</FormattedPri
Is there something I don't know about HttpWebRequest or Amazon's API?
the url (don't care about the key) edit: bad idea, limit exceeded...
This worked for me:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
Stream s = response.GetResponseStream();
using (StreamReader sr = new StreamReader(s))
{
s.Flush();
resultString = sr.ReadToEnd();
...
}
I am encountering an unusually strange behavior when POSTing a Json string to a PHP webserver. I use the JsonTextWriter object to create the Json string. I then send the Json string as a POST request. Please see comments. The HTML response in the code is returning the correct output, but when viewed in a browser, the web page displays either NULL or array(0) { }.
private void HttpPost(string uri, string parameters)
{
WebRequest webRequest = WebRequest.Create(uri);
webRequest.ContentType = "application/x-www-form-urlencoded"; // <- Should this be "application/json" ?
webRequest.Method = "POST";
byte[] bytes = Encoding.UTF8.GetBytes(parameters);
string byteString = Encoding.UTF8.GetString(bytes);
Stream os = null;
try
{ // Send the Post Data
webRequest.ContentLength = bytes.Length;
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
Console.WriteLine(String.Format(#"{0}", byteString)); // <- This matches the Json object
}
catch (WebException ex)
{ //Handle Error }
try
{ // Get the response
WebResponse webResponse = webRequest.GetResponse();
if (webResponse == null) { return null; }
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim()); // <- Server returns string response (full HTML page)
}
catch (WebException ex)
{ //Handle Error }
}
Relevant PHP code on the server:
$json = json_encode($_POST); # Not 'standard way'
var_dump(json_decode($json));
Any suggestions would be greatly appreciated.
Thanks
Try using "application/json" as the content type. Also, check the request logs or maybe do a port 80 trace if you can to view what's being sent to the server in the request body.
You can also narrow the scope of the problem -- is it the C# code or the PHP code that's bad -- by writing a quick JQuery ajax function that sends some JSON to the PHP server. This isolation of the PHP code from the C# code will tell you if the PHP is at least working correctly. If it is, then the problem is in the C# code.