C#を勉強しておりこの度NiftyCloudのAPIの利用を試みました。
自分なりに挑戦しましたがうまくいきません。
有識者の方いましたら間違いをご教示ください。
API利用の流れですがniftycloudのapiはGETリクエストでURLにエンコードしたパラメーターを付与して利用します。
また各APIを利用するために、利用するAPI特有のパラメーター以外に共通パラメーター(CommonParam)を付与する必要があります。
この共通パラメーターの部分で2つ不明な点がありましたのでサンプルをコピペしました。
そこが間違えている可能性がありますが詳しくはソースコードのコメントに記載しております。
[エンドポイント] https://cloud.nifty.com/api/endpoint.htm [共通パラメーター] https://cloud.nifty.com/api/rest/authenticate.htm [API] https://cloud.nifty.com/api/rest/RunInstances.htm
下記ソースコードではRunInstances APIでサーバーの作成を試みたものです。
ソースコードにコメントを記載しておりますのでご覧いただければと思います。
lang
1 static void Main(string[] args) 2 { 3 4 ///////////////////////////////////シグネチャー(共通パラメーターの内の1つ)を生成///////////////////////////////////////////// 5 6 //シグネチャー作成やAPIを利用する際に必要なパラメーターの定義 7 string AccesKeyId = "Himitu"; 8 string Action = "RunInstances"; 9 string SignatureMethod = "HmacSHA256"; 10 string SignatureVersion = "2"; 11 //タイムスタンプの作成 12 var localtime = DateTime.Now; 13 var timestamp = localtime.ToString("yyyy-MM-ddTHH:mm:ssZ"); 14 15 //シグネチャー作成のためにパラメーターをエンコード 16 var content = new FormUrlEncodedContent(new Dictionary<string, string> 17 18 { 19 20 {"AccessKeyId",AccesKeyId}, 21 22 {"Action",Action}, 23 24 {"SignatureMethod",SignatureMethod }, 25 26 {"SignatureVersion",SignatureVersion}, 27 28 {"Timestamp",timestamp} 29 30 }); 31 32 //シグネチャー作成やAPIを利用する際に必要なパラメーターの定義 33 34 string HTTP_request_method = "GET"; 35 string endpoint_domain = "jp-east-1.computing.api.nifcloud.com"; 36 37 //[不明点1]URLエンコードしたendpointのパス部分の意味が分からないのでサンプルのコピペ 38 string urlencoded_endpoint = "/api/services/NiftyCloud/"; 39 40 //[不明点2]サンプルではendpoint_domainの後に\nとあったがのでそのままサンプルのコピペ 41 string StringToSign = HTTP_request_method + "\n" + endpoint_domain + "\n" + urlencoded_endpoint + "\n"+content.ReadAsStringAsync().Result; 42 43 string SecretKeyId = "Himitu"; 44 45 //HMACSHA256とStringToSign,SecretKeyIdを利用してシグネチャーを生成 46 var Signature = ""; 47 48 ASCIIEncoding encoding = new ASCIIEncoding(); 49 Byte[] StringToSignByte = encoding.GetBytes(StringToSign); 50 Byte[] AccesKeyIDByte = encoding.GetBytes(SecretKeyId); 51 52 Byte[] hashBytes; 53 using (HMACSHA256 hash = new HMACSHA256(AccesKeyIDByte)) 54 { 55 hashBytes = hash.ComputeHash(StringToSignByte); 56 Signature = BitConverter.ToString(hashBytes).Replace("-", "").ToLower(); 57 } 58 59 ///////////////////////////////////////////////////////////ここまでがシグネチャーの作成////////////////////////////////////////////// 60 61 //RunInstances API利用するために必要なパラメーター 62 string ImageId = "1"; 63 string KeyName = "nifcloud"; 64 string InstanceType = "e-mini"; 65 string InstanceId = "server01"; 66 string servername = "serve01"; 67 string servertype = "e-mini"; 68 string AccountingType = "2"; 69 70 var parameters = new FormUrlEncodedContent(new Dictionary<string, string> 71 { 72 {"Action",Action }, 73 {"ImageId",ImageId}, 74 {"KeyName",KeyName}, 75 {"InstanceType",InstanceType}, 76 {"InstanceId",InstanceId}, 77 //以下のパラメーターはCommonParames部分 78 {"AccessKeyId",AccesKeyId}, 79 {"SignatureVersion",SignatureVersion}, 80 {"Signature",Signature}, 81 {"Timestamp",timestamp}, 82 {"SignatureMethod","HmacSHA256"} 83 }); 84 85 86 87 string endpoint = "https://jp-east-1.computing.api.nifcloud.com/api/"; 88 getAPI(endpoint, parameters); 89 Console.ReadKey(); 90 } 91 92 //HTTPClientを利用してGETリクエストを送る関数 93 static async void getAPI(string url, FormUrlEncodedContent param) 94 { 95 using (var client = new HttpClient()) 96 { 97 98 var response = await client.GetAsync(url+"?"+param.ReadAsStringAsync().Result); 99 Console.WriteLine(response); 100 Console.WriteLine(response.StatusCode); 101 Console.WriteLine(response.Content); 102 Console.WriteLine(response.ToString()); 103 } 104 105 } 106 107 108 } 109 110
このコードを動かしたところ下記のResponseが帰ってきました。
StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.NoWriteNoSeekStreamContent, Headers: { Connection: close Date: Sat, 13 Oct 2018 15:16:10 GMT Server: Apache Content-Length: 298 Content-Type: application/xml Content-Encoding: UTF-8 } InternalServerError System.Net.Http.NoWriteNoSeekStreamContent StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.NoWriteNoSeekStreamContent, Headers: { Connection: close Date: Sat, 13 Oct 2018 15:16:10 GMT Server: Apache Content-Length: 298 Content-Type: application/xml Content-Encoding: UTF-8 }
APIを利用するにあたって利用したサイトも貼っておきます。
[今更ですがHttpClientを使う] https://qiita.com/rawr/items/f78a3830d894042f891b#%E3%82%AF%E3%82%A8%E3%83%AA%E3%83%91%E3%83%A9%E3%83%A1%E3%83%BC%E3%82%BF%E3%82%92%E9%80%81%E3%82%8B [NIFTY CloudのREST APIを使うために必要な知識] http://naoberry.com/tech/rest-api/ [NIFTY Cloud APIをRubyから使ってみる!] http://blogs.itmedia.co.jp/niftycloud/2011/08/nifty-cloud-api-0052.html