Skip to content

Instantly share code, notes, and snippets.

@ALiwoto
Created July 27, 2021 10:23
Show Gist options
  • Save ALiwoto/ba66476e0fb665e185595be169c7d05f to your computer and use it in GitHub Desktop.
Save ALiwoto/ba66476e0fb665e185595be169c7d05f to your computer and use it in GitHub Desktop.
Dank class for showing how to send a graphquery in C#
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Collections;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.Json.Serialization;
using System.Text.Json;
namespace LTW.Screens
{
public static class Dank
{
public const string QueryValue = @"
query ($search: String) {
Media (search: $search) {
id
title {
romaji
english
native
}
type
format
status
description
episodes
bannerImage
externalLinks{
url
}
duration
chapters
volumes
genres
synonyms
averageScore
airingSchedule(notYetAired: true) {
nodes {
airingAt
timeUntilAiring
episode
}
}
siteUrl
}
}
";
public static ApiClass ApiRequest(string param)
{
if (string.IsNullOrWhiteSpace(param))
{
throw new Exception("parameter cannot be null or empty");
}
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://graphql.anilist.co");
var data = GetQueryData(param);
request.Method = "POST";
request.ContentType = "application/json"; // place MIME type here
request.ContentLength = data.Length;
//var client = new HttpClient();
var resp = request.GetResponse();
if (resp == null)
{
return null;
}
var receiveStream = resp.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
// create a new stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, encode);
Console.WriteLine("\nResponse stream received");
Char[] read = new Char[256];
// Read 256 charcters at a time.
int count = readStream.Read(read, 0, 256);
string str = string.Empty;
while (count > 0)
{
// Dump the 256 characters on a string and display the string onto the console.
string tmpStr = new String(read, 0, count);
// remove all whitespaces
str += tmpStr.Trim();
count = readStream.Read(read, 0, 256);
}
// Release the resources of stream object.
readStream.Close();
// Release the resources of response object.
resp.Close();
var apiResponse = JsonSerializer.Deserialize(str, typeof(ApiClass));
if (apiResponse is ApiClass a)
{
return a;
}
return null;
// when working with Newtonsoft.Json
//return JsonConverter.DeserializeObject<ApiClass>(str);
}
private static byte[] GetQueryData(string searchValue)
{
var variablesMap = new Hashtable()
{
{"search", searchValue},
};
var h = new Hashtable()
{
{"query", QueryValue},
{"variables", variablesMap}
};
var s = JsonSerializer.Serialize(h, h.GetType());
return Encoding.Default.GetBytes(s);
}
}
public class ApiClass
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment