C# (dotnetcore) HttpClientを利用してredmineのAPIを叩く(プロジェクト一覧)
注意
単純なコンソールプログラムのため、 HttpClientをusingで囲わないでくださいという警告を無視しています。
redmineを準備
今回テストで利用するプロジェクトです。
ブラウザでアクセスした結果
APIにブラウザでアクセスすると、以下のような結果になります。
今回は、上記XMLをc#でリクエストし、取得したXMLを解析するところまでやってみたいと思います。
単純にリクエストするプログラムの作成
using System; using System.Net.Http; namespace redmineApiExample { class Program { /// <summary> /// redmineのURLを指定 /// </summary> static string C_REDMINE_URL { get { return "https://~~省略~~.co.jp"; } } /// <summary> /// redmineのAPIキーを指定 /// </summary> static string C_API_KEY { get { return "~~省略~~"; } } static void Main(string[] args) { //urlを組み立てる var url = C_REDMINE_URL + "/projects.xml?key=" + C_API_KEY; //HttpClientのオブジェクト生成 using (var client = new HttpClient()) { //GET操作実行 var responseMessage = client.GetAsync(url).Result; //ステータスコードのチェック if (responseMessage.IsSuccessStatusCode) { //HTTPのBody部分を取得 var httpContent = responseMessage.Content; //HTTPのBody部分をString型で取得 var responseString = httpContent.ReadAsStringAsync().Result; Console.WriteLine(responseString); } } } } }
結果
XMLの文字列が取得できました。
<?xml version="1.0" encoding="UTF-8"?><projects total_count="1" offset="0" limit="25" type="array"><project><id>10</id><name>テストプロジェクト</name><identifier>test-project</identifier><description>テスト用のプロジェクト</description><status>1</status><is_public>false</is_public><created_on>2020-09-04T14:27:28Z</created_on><updated_on>2020-09-04T14:27:28Z</updated_on></project></projects>
XMLを解析するプログラムを記述
取得したXMLをXElementを利用して解析します。
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Xml.Linq; namespace redmineApiExample { class Program { //~~C_REDMINE_URLとC_API_KEYは省略~~ static void Main(string[] args) { //urlを組み立てる var url = C_REDMINE_URL + "/projects.xml?key=" + C_API_KEY; //HttpClientのオブジェクト生成 using (var client = new HttpClient()) { //GET操作実行 var responseMessage = client.GetAsync(url).Result; //ステータスコードのチェック if (responseMessage.IsSuccessStatusCode) { //HTTPのBody部分を取得 var httpContent = responseMessage.Content; //HTTPのBody部分をString型で取得 var responseString = httpContent.ReadAsStringAsync().Result; //Console.WriteLine(responseString); var xml = XElement.Parse(responseString); foreach (var project in xml.Elements("project")) { Console.WriteLine("id:" + project.Element("id").Value); Console.WriteLine("name:" + project.Element("name").Value); Console.WriteLine("identifier:" + project.Element("identifier").Value); Console.WriteLine("description:" + project.Element("description").Value); Console.WriteLine("status:" + project.Element("status").Value); Console.WriteLine("is_public:" + project.Element("is_public").Value); Console.WriteLine("created_on:" + project.Element("created_on").Value); Console.WriteLine("updated_on:" + project.Element("updated_on").Value); } } } } } }
実行
projectエレメントの内容をコンソールに出力することができました。