CでVK APIを使用する#

読者の皆様、ご挨拶! この記事では、VKontakteソーシャルネットワークAPIで動作する最も簡単なWindowsFormsアプリケーションを作成するプロセスについて説明します。



アプリケーションタスク:



  1. ユーザートークンを取得し、それを使用してそれ以降のすべてのリクエストを実行します。
  2. 入力でユーザーIDを取得します。
  3. 入力されたIDを持つユーザーに関する情報を表示します。


UPD: GitHubのリポジトリ

UPD(2018年9月26日):リクエストに 'version'パラメーターが追加されました。 トークンを受信するときにオートコンプリートアプリケーションIDを追加しました。 警告が追加されました。

警告:使用されているAPIバージョンは5.52です。 2018年9月26日、後者は5.85です。 APIバージョン5.8以降、プログラムは機能しません。これは、数値ではなくオブジェクトが「city」および「country」フィールドに返されるためです。



便宜上、2つのライブラリを使用します。





最初に行うことは、アプリケーションIDを取得することです。 これを行うには、 VkDevelopersに移動し、新しいスタンドアロンアプリケーションを作成し、設定に移動してApplicationIDをコピーします。



アプリケーションの作成を開始し、VisualStudioに移動して、新しいWindowsFormsアプリケーションを作成できます。



図書館をつなぐ
JSON.Netライブラリーは、パッケージマネージャーコンソールを使用して接続されます。コマンドを入力するだけです:
インストールパッケージNewtonsoft.Json


xNetライブラリを接続するには、 ここにアクセスし 、xNet.dllをダウンロードし、リンクマネージャーを使用してプロジェクトに追加する必要があります。


ライブラリを接続した後、MainForm(標準のForm1を使用できます)とAuthorizationFormの2つのフォームを作成します。 フォームは次のようになります。



メインフォーム




AuthorizationForm
このフォームは、パラメーターName = GetTokenのWebBrowser要素で構成されます。



別のクラスファイルを作成します。 VkAPIと呼びましょう。



コードの書き始め。



最初に、トークンの受信を実装します。 これを行うには、MainFormで、Button_GetTokenボタンをクリックするためのハンドラーを作成します。



private void Button_GetToken_Click(object sender, EventArgs e) { AuthorizationForm GetToken = new AuthorizationForm(); GetToken.ShowDialog(); }
      
      





 using System; using System.Windows.Forms; using System.IO; namespace VkAPITutorial { public partial class AuthorizationForm : Form { public AuthorizationForm() { InitializeComponent(); } private void AuthorizationForm_Load(object sender, EventArgs e) { GetToken.DocumentCompleted += GetToken_DocumentCompleted; GetToken.Navigate("https://oauth.vk.com/authorize?client_id="+ VkAPI.__APPID +"&display=page&redirect_uri=https://oauth.vk.com/blank.html&scope=friends&response_type=token&v=5.52"); } private void GetToken_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { if (GetToken.Url.ToString().IndexOf("access_token=") != -1) { GetUserToken(); } } private void GetUserToken() { char[] Symbols = { '=', '&' }; string[] URL = GetToken.Url.ToString().Split(Symbols); File.WriteAllText("UserInf.txt", URL[1] + "\n"); File.AppendAllText("UserInf.txt", URL[5]); this.Visible = false; } private void GetToken_DocumentCompleted_1(object sender, WebBrowserDocumentCompletedEventArgs e){} } }
      
      





それでは順番に整理しましょう:



ボタンをクリックすると、WebブラウザでAuthorizationFormが開き、ブラウザでリンクが開きます。
  https://oauth.vk.com/authorize?client_id=ApplicationID&display=page&redirect_uri=https://oauth.vk.com/blank.html&scope=friends&response_type=token&v=5.52 


client_idパラメーターは、記事の冒頭で受け取ったアプリケーションIDです。 スコープパラメーターの後に、要求するアクセス許可が一覧表示されます 。アクセス許可の完全な一覧については、 こちらをご覧ください



ページを更新するときに、アドレスにaccess_tokenが含まれているかどうかを確認し、 含まれている場合は、アドレスを分割して、トークンファイルとログインしたユーザーのIDを格納します。 その後、AuthorizationFormが閉じます。 トークンを受け取りました!



これで、ユーザーに関する情報の受信と表示を開始できます。 名前、姓、都市、国、写真を取得する必要があります。 リクエストごとに個別に受信することもできますが、1つのリクエストで受信することをお勧めします。



ファイルVkAPI.csを編集します。



 using System.Collections.Generic; using xNet; using Newtonsoft.Json; namespace VkAPITutorial { class VkAPI { public const string __APPID = "APPLICATION_ID"; //ID  private const string __VKAPIURL = "https://api.vk.com/method/"; //   private string _Token; //,    public VkAPI(string AccessToken) { _Token = AccessToken; } public Dictionary<string, string> GetInformation(string UserId, string[] Fields) //       ID { HttpRequest GetInformation = new HttpRequest(); GetInformation.AddUrlParam("user_ids", UserId); GetInformation.AddUrlParam("access_token", _Token); GetInformation.AddUrlParam("version", "5.52"); string Params = ""; foreach (string i in Fields) { Params += i + ","; } Params = Params.Remove(Params.Length - 1); GetInformation.AddUrlParam("fields", Params); string Result = GetInformation.Get(__VKAPIURL + "users.get").ToString(); Result = Result.Substring(13, Result.Length - 15); Dictionary<string, string> Dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(Result); return Dict; } public string GetCityById(string CityId) // ID    { HttpRequest GetCityById = new HttpRequest(); GetCityById.AddUrlParam("city_ids", CityId); GetCityById.AddUrlParam("access_token", _Token); GetCityById.AddUrlParam("version", "5.52"); string Result = GetCityById.Get(__VKAPIURL + "database.getCitiesById").ToString(); Result = Result.Substring(13, Result.Length - 15); Dictionary<string, string> Dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(Result); return Dict["name"]; } public string GetCountryById(string CountryId) // ID    { HttpRequest GetCountryById = new HttpRequest(); GetCountryById.AddUrlParam("country_ids", CountryId); GetCountryById.AddUrlParam("access_token", _Token); GetCountryById.AddUrlParam("version", "5.52"); string Result = GetCountryById.Get(__VKAPIURL + "database.getCountriesById").ToString(); Result = Result.Substring(13, Result.Length - 15); Dictionary<string, string> Dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(Result); return Dict["name"]; } } }
      
      





そしてMainForm:



 using System; using System.Windows.Forms; using System.Collections.Generic; using System.IO; namespace VkAPITutorial { public partial class MainForm : Form { VkAPI _ApiRequest; private string _Token; //,    private string _UserId; //ID  private Dictionary<string, string> _Response; //   public MainForm() { InitializeComponent(); } private void Button_GetToken_Click_1(object sender, EventArgs e) { AuthorizationForm GetToken = new AuthorizationForm(); GetToken.ShowDialog(); } private void MainForm_Load(object sender, EventArgs e) { try { StreamReader ControlInf = new StreamReader("UserInf.txt"); _Token = ControlInf.ReadLine(); _UserId = ControlInf.ReadLine(); ControlInf.Close(); if (_Token != null) { _ApiRequest = new VkAPI(_Token); string[] Params = { "city", "country", "photo_max" }; _Response = _ApiRequest.GetInformation(_UserId, Params); if (_Response != null) { User_ID.Text = _UserId; User_Photo.ImageLocation = _Response["photo_max"]; User_Name.Text = _Response["first_name"]; User_Surname.Text = _Response["last_name"]; User_Country.Text = _ApiRequest.GetCountryById(_Response["country"]); User_City.Text = _ApiRequest.GetCityById(_Response["city"]); Button_GetToken.Visible = false; } } } catch { } } private void Button_GetInformation_Click_1(object sender, EventArgs e) { try { StreamReader ControlInf = new StreamReader("UserInf.txt"); _Token = ControlInf.ReadLine(); ControlInf.Close(); _ApiRequest = new VkAPI(_Token); _UserId = User_ID.Text; string[] Params = { "city", "country", "photo_max" }; _Response = _ApiRequest.GetInformation(_UserId, Params); if (_Response != null) { User_ID.Text = _UserId; User_Photo.ImageLocation = _Response["photo_max"]; User_Name.Text = _Response["first_name"]; User_Surname.Text = _Response["last_name"]; User_Country.Text = _ApiRequest.GetCountryById(_Response["country"]); User_City.Text = _ApiRequest.GetCityById(_Response["city"]); Button_GetToken.Visible = false; } } catch { } } } }
      
      





コードを分析しましょう:



起動時に、アプリケーションはトークンとユーザーIDの読み取りを試みます。



 StreamReader ControlInf = new StreamReader("UserInf.txt"); _Token = ControlInf.ReadLine(); _UserId = ControlInf.ReadLine(); ControlInf.Close();
      
      





読み取りが成功した場合、アプリケーションはユーザーに関する情報を要求しようとします(トークン検証チェック):



 _ApiRequest = new VkAPI(_Token); string[] Params = { "city", "country", "photo_max" }; _Response = _ApiRequest.GetInformation(_UserId, Params);
      
      





リクエストが成功すると、フォームのすべてのフィールドに入力され、GetTokenボタンが非アクティブになります。



 User_ID.Text = _UserId; User_Photo.ImageLocation = _Response["photo_max"]; User_Name.Text = _Response["first_name"]; User_Surname.Text = _Response["last_name"]; User_Country.Text = _ApiRequest.GetCountryById(_Response["country"]); User_City.Text = _ApiRequest.GetCityById(_Response["city"]); Button_GetToken.Visible = false;
      
      





それ以外の場合、GetTokenボタンがアクティブになり、クリックすると関数が機能します。



  private void Button_GetInformation_Click(object sender, EventArgs e) { try { StreamReader ControlInf = new StreamReader("UserInf.txt"); _Token = ControlInf.ReadLine(); ControlInf.Close(); _ApiRequest = new VkAPI(_Token); _UserId = User_ID.Text; string[] Params = { "city", "country", "photo_max" }; _Response = _ApiRequest.GetInformation(_UserId, Params); if (_Response != null) { User_ID.Text = _UserId; User_Photo.ImageLocation = _Response["photo_max"]; User_Name.Text = _Response["first_name"]; User_Surname.Text = _Response["last_name"]; User_Country.Text = _ApiRequest.GetCountryById(_Response["country"]); User_City.Text = _ApiRequest.GetCityById(_Response["city"]); Button_GetToken.Visible = false; } } catch { } }
      
      





GETリクエストがどのように発生するかを見てみましょう。 最初に変数が作成されます:



 HttpRequest GetInformation = new HttpRequest();
      
      





次に、パラメーターが入力されます。



 GetInformation.AddUrlParam("user_ids", UserId); GetInformation.AddUrlParam("access_token", _Token); GetInformation.AddUrlParam("version", "5.52"); string Params = ""; foreach (string i in Fields) { Params += i + ","; } Params = Params.Remove(Params.Length - 1); GetInformation.AddUrlParam("fields", Params);
      
      





そして、GETリクエストが行われます:



 string Result = GetInformation.Get(__VKAPIURL + "users.get").ToString();
      
      





結果は、変換可能な文字列にトリミングされます。



 Result = Result.Substring(13, Result.Length - 15);
      
      





JSONを辞書に変換します。



 Dictionary<string, string> Dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(Result);
      
      





小さなアプリケーションの準備ができました! ご清聴ありがとうございました! あなたのコメントを聞く準備ができています。



All Articles