-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGithubClient.cs
71 lines (58 loc) · 2.18 KB
/
GithubClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization.Json;
using System.Threading.Tasks;
namespace WebAPIClient
{
public class GithubClient
{
private HttpClient client;
public GithubClient()
{
client = new HttpClient();
// add custom github headers for JSON access
var headers = client.DefaultRequestHeaders;
headers.Accept.Clear();
headers.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));
headers.Add("User-Agent", ".NET Foundation Repository Reporter");
}
/**
* Get the repos for a given owner.
*/
public async Task<SearchResult> PerformSearch(EscapedString query)
{
var root = "https://api.github.com/search/repositories";
var parameter = "?q=";
var serializer = new DataContractJsonSerializer(typeof(SearchResult));
var streamTask = client.GetStreamAsync(root + parameter + query);
// Parse the JSON using a stream, to the model object
return serializer.ReadObject(await streamTask) as SearchResult;
}
/**
* Get the repos for a given owner.
*/
public async Task<List<Repository>> ProcessRepositories(EscapedString owner)
{
var serializer = new DataContractJsonSerializer(typeof(List<Repository>));
var url = String.Format("https://api.github.com/orgs/{0}/repos", owner);
var streamTask = client.GetStreamAsync(url);
return serializer.ReadObject(await streamTask) as List<Repository>;
}
/**
* Prints the first 500 characters of the stream to console.
* Useful if you have no idea what a http request is returning.
*/
private async void debugHttp(Task<Stream> streamTask)
{
var reader = new StreamReader(await streamTask);
for (var i = 0; i < 500; i++)
{
Console.Write((char)reader.Read());
}
}
}
}