質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.51%
C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

Q&A

解決済

3回答

4845閲覧

C# CoincheckのAPIを実行したい。

AMK

総合スコア765

C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

1グッド

0クリップ

投稿2017/04/28 08:56

お世話になります。
C#の勉強をしたいと思い
下記のサイトより
https://kokenji.net/coincheck-api/
コードを拝借してAPIを実行してみましたが

どうしてもinternal async Task<string>Sendの部分で
CS0116のエラーが回避出来ず先輩方のお力をお借りしようと思い書き込みをさせていただきました。

丸投げするのも自分のためにならないので
このサイトを見たら解決できるやヒントなどを頂けると助かります。

お忙しいところ大変恐縮ですがよろしくお願いします
コードは下記のとおりです。

C#

1using System; 2using System.Collections.Generic; 3using System.Net.Http; 4using System.Security.Cryptography; 5using System.Text; 6using System.Threading.Tasks; 7using System.Windows.Forms; 8namespace Crypto_Currency 9{ 10 public partial class Form1 : Form 11 { 12 public Form1() 13 { 14 InitializeComponent(); 15 } 16 17 private void Form1_Load(object sender, EventArgs e) 18 { 19 20 } 21 22 private async void button1_ClickAsync(object sender, EventArgs e) 23 { 24 //coincheck取引所にアクセスする HttpClient 25 HttpClient http = new HttpClient(); 26 http.BaseAddress = new Uri("https://coincheck.com"); 27 28 //板情報を取得 29 Uri path = new Uri("/api/order_books", UriKind.Relative);//APIの通信URL 30 string apiKey = "XXXXX";//APIキー 31 string secret = "XXXXX";//秘密キー 32 string method = "GET";//APIメソッド 33 string json = await Send(http, path, apiKey, secret, method); 34 35 36 } 37 } 38 39/// <summary>coincheck取引所のAPIを実行します。 40/// </summary> 41/// <param name="http">取引所と通信する HttpClient。</param> 42/// <param name="path">APIの通信URL(取引所サイトからの相対)。</param> 43/// <param name="apiKey">APIキー。</param> 44/// <param name="secret">秘密キー。</param> 45/// <param name="method">APIのメソッド名。</param> 46/// <param name="parameters">APIのパラメータのリスト(Key:パラメータ名, Value:パラメータの値)。</param> 47/// <returns>レスポンスとして返されるJSON形式の文字列。</returns> 48internal async Task<string> Send(HttpClient http, Uri path, string apiKey, string secret, string method, Dictionary<string, string> parameters = null) 49{ 50 if (parameters == null) 51 parameters = new Dictionary<string, string>(); 52 53 // パラメータ文字列を作成 54 var content = new FormUrlEncodedContent(parameters); 55 string param = await content.ReadAsStringAsync(); 56 57 // nonceにunixtimeを用いる 58 string nonce = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(); 59 60 // POSTするメッセージを作成 61 var uri = new Uri(http.BaseAddress, path); 62 string message = nonce + uri.ToString() + param; 63 64 // メッセージをHMACSHA256で署名 65 byte[] hash = new HMACSHA256(Encoding.UTF8.GetBytes(secret)).ComputeHash(Encoding.UTF8.GetBytes(message)); 66 string sign = BitConverter.ToString(hash).ToLower().Replace("-", "");//バイト配列をを16進文字列へ 67 68 // HTTPヘッダをセット 69 http.DefaultRequestHeaders.Clear(); 70 http.DefaultRequestHeaders.Add("ACCESS-KEY", apiKey); 71 http.DefaultRequestHeaders.Add("ACCESS-NONCE", nonce); 72 http.DefaultRequestHeaders.Add("ACCESS-SIGNATURE", sign); 73 74 // 送信 75 HttpResponseMessage res; 76 if (method == "POST") 77 { 78 res = await http.PostAsync(path, content); 79 } 80 else if (method == "GET") 81 { 82 res = await http.GetAsync(path); 83 } 84 else 85 { 86 throw new ArgumentException("method は POST か GET を指定してください。", method); 87 } 88 89 //返答内容を取得 90 string text = await res.Content.ReadAsStringAsync(); 91 92 //通信上の失敗 93 if (!res.IsSuccessStatusCode) 94 return ""; 95 96 return text; 97} 98}
hihijiji👍を押しています

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答3

0

ベストアンサー

こんにちは。

コメントを見て少し気になったので回答してみます。

Classで囲ったアプローチは間違っていないのか?

class Programでメソッドを囲むことでエラーが出なくなることを発見したのは素晴らしいことです。しかし、「なぜclassで囲むことでエラーが出なくなったのか?」を考えるところまで至っていないのが非常にもったいなく感じます。
真面目に解決を目指すなら、「質問のコードを動作させること」より「構文を覚え、その意味を理解すること」を優先するほうが、遠回りですが確実です。

まずは、以下のサイトで「基礎」より下を一通り読んでみることをオススメします。
C# によるプログラミング入門 | ++C++; // 未確認飛行 C

投稿2017/04/30 04:46

tamoto

総合スコア4103

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

AMK

2017/05/01 05:04

ありがとうございます。 お陰様で解決できました!! まだ理解はできていませんが・・・・w ネームスペースから場所を指定しなければダメだったのが原因ですね。 string json = await Send(http, path, apiKey, secret, method); を string json = await Program.Send(http, path, apiKey, secret, method); に internal async Task<string> Send を internal static async Task<string> Send にしてstaticを追加したら動きました!!
guest

0

答えではなくヒントということなので。

Compiler Error CS0116

名前空間にフィールドやメソッドのようなメンバーを直接含めることはできません。

投稿2017/04/28 09:19

workaholist

総合スコア559

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

AMK

2017/04/29 18:17

ヒントありがとうございます。 internal async Taskの部分をClass Programで囲ったらエラーはCS0116エラーは発生しなくなりました!! ありがとうございます。 次に string json = await Send(http, path, apiKey, secret, method);の部分でSendと言う名前は存在しません。CS0103のエラーが出てしまいました。 Classで囲ったアプローチは間違っていないのか? ヒント又は参考URLなど教えて頂くと助かります。
guest

0

完成系のコード

VS2017で作成
.net 4.6以上を指定する事!
Windowsフォーム アプリケーションで作成

C#

1//Program.cs 2using System; 3using System.Collections.Generic; 4using System.Linq; 5using System.Net.Http; 6using System.Security.Cryptography; 7using System.Text; 8using System.Threading.Tasks; 9using System.Windows.Forms; 10 11namespace Crypto_Currency 12{ 13 14 public class Program 15 { 16 /// <summary> 17 /// アプリケーションのメイン エントリ ポイントです。 18 /// </summary> 19 [STAThread] 20 static void Main() 21 { 22 Application.EnableVisualStyles(); 23 Application.SetCompatibleTextRenderingDefault(false); 24 Application.Run(new Form1()); 25 } 26 27 /// <summary>coincheck取引所のAPIを実行します。 28 /// </summary> 29 /// <param name="http">取引所と通信する HttpClient。</param> 30 /// <param name="path">APIの通信URL(取引所サイトからの相対)。</param> 31 /// <param name="apiKey">APIキー。</param> 32 /// <param name="secret">秘密キー。</param> 33 /// <param name="method">APIのメソッド名。</param> 34 /// <param name="parameters">APIのパラメータのリスト(Key:パラメータ名, Value:パラメータの値)。</param> 35 /// <returns>レスポンスとして返されるJSON形式の文字列。</returns> 36 internal static async Task<string> Send(HttpClient http, Uri path, string apiKey, string secret, string method, Dictionary<string, string> parameters = null) 37 //internal async Task<string> Send(HttpClient http, Uri path, string apiKey, string secret, string method, Dictionary<string, string> parameters = null) 38 { 39 if (parameters == null) 40 parameters = new Dictionary<string, string>(); 41 42 // パラメータ文字列を作成 43 var content = new FormUrlEncodedContent(parameters); 44 string param = await content.ReadAsStringAsync(); 45 46 // nonceにunixtimeを用いる 47 string nonce = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(); 48 49 // POSTするメッセージを作成 50 var uri = new Uri(http.BaseAddress, path); 51 string message = nonce + uri.ToString() + param; 52 53 // メッセージをHMACSHA256で署名 54 byte[] hash = new HMACSHA256(Encoding.UTF8.GetBytes(secret)).ComputeHash(Encoding.UTF8.GetBytes(message)); 55 string sign = BitConverter.ToString(hash).ToLower().Replace("-", "");//バイト配列をを16進文字列へ 56 57 // HTTPヘッダをセット 58 http.DefaultRequestHeaders.Clear(); 59 http.DefaultRequestHeaders.Add("ACCESS-KEY", apiKey); 60 http.DefaultRequestHeaders.Add("ACCESS-NONCE", nonce); 61 http.DefaultRequestHeaders.Add("ACCESS-SIGNATURE", sign); 62 63 // 送信 64 HttpResponseMessage res; 65 if (method == "POST") 66 { 67 res = await http.PostAsync(path, content); 68 } 69 else if (method == "GET") 70 { 71 res = await http.GetAsync(path); 72 } 73 else 74 { 75 throw new ArgumentException("method は POST か GET を指定してください。", method); 76 } 77 78 //返答内容を取得 79 string text = await res.Content.ReadAsStringAsync(); 80 81 //通信上の失敗 82 if (!res.IsSuccessStatusCode) 83 return ""; 84 85 return text; 86 } 87} 88} 89 90 91//From1.cs 92using System; 93using System.Collections.Generic; 94using System.Net.Http; 95using System.Security.Cryptography; 96using System.Text; 97using System.Threading.Tasks; 98using System.Windows.Forms; 99 100namespace Crypto_Currency 101{ 102 public partial class Form1 : Form 103 { 104 public Form1() 105 { 106 InitializeComponent(); 107 } 108 109 private async void button1_ClickAsync(object sender, EventArgs e) 110 { 111 //coincheck取引所にアクセスする HttpClient 112 HttpClient http = new HttpClient(); 113 http.BaseAddress = new Uri("https://coincheck.com"); 114 115 //板情報を取得 116 Uri path = new Uri("/api/order_books", UriKind.Relative);//APIの通信URL 117 string apiKey = "APIキー";//APIキー 118 string secret = "秘密キー";//秘密キー 119 string method = "GET";//APIメソッド 120 string json = await Program.Send(http, path, apiKey, secret, method); 121 122 textBox1.Text = json; 123 } 124 } 125} 126

投稿2017/05/01 05:12

AMK

総合スコア765

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.51%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問