• [C#]新PixivAPI叩いてみた

    2015-05-21 17:54
    KBTIT犯してみた
    セクション毎にGistへのリンクが張ってあります。
    パーサはJson.NETを使用しています。

    参考
    Pixiv Public-API (OAuth)分析 - pixivpy新版本放出 http://blog.imaou.com/opensource/2014/10/09/pixiv_api_for_ios_update.html


    ログイン&セッションID・トークン取得

    static void Login(string userid, string password)
    {
     string postData = "username=" + PixivID + "&password=" + password + "&grant_type=password&client_id=bYGKuGVw91e0NMfPGp44euvGt59s&client_secret=HP3RmkgAmEGro0gn1x9ioawQE8WMfvLXDz3ZqxpK";
     byte[] postDataBytes = System.Text.Encoding.ASCII.GetBytes(postData);

     try
     {
      HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://oauth.secure.pixiv.net/auth/token");
      req.Method = "POST";
      req.ContentType = "application/x-www-form-urlencoded";
      req.ContentLength = postDataBytes.Length;
      req.Referer = "http://www.pixiv.net/";
      req.UserAgent = "PixivIOSApp/5.1.1";
      System.IO.Stream reqStream = req.GetRequestStream();
      reqStream.Write(postDataBytes, 0, postDataBytes.Length);
      reqStream.Close();
      System.Net.WebResponse res = req.GetResponse();
      System.IO.Stream resStream = res.GetResponseStream();
      System.IO.StreamReader sr = new System.IO.StreamReader(resStream, enc);
      string response = sr.ReadToEnd();
      string header = res.Headers["Set-Cookie"];
      sr.Close();
      Regex r = new System.Text.RegularExpressions.Regex("access_token\":\"(.*?)\",", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline);
      MatchCollection mc = r.Matches(response);
      foreach (System.Text.RegularExpressions.Match m in mc)
      {
       token = m.Groups[1].Value;
      }
      r = new System.Text.RegularExpressions.Regex("PHPSESSID=(.*?);", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline);
      mc = r.Matches(header);
      foreach (System.Text.RegularExpressions.Match m in mc)
      {
       sessid = m.Groups[1].Value;
      }

      Console.WriteLine("トークン: "+token);
      Console.WriteLine("SESSID: ":sessid);

     }
     catch(WebException)
     {
      MessageBox.Show("ログインに失敗しました", "teihe", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }

     return;
    }


    JSONパーサ用クラス

     public class Pixiv
     {
      public class Pagination
      {
       public int current { get; set; }
       public object next { get; set; }
       public int pages { get; set; }
       public int per_page { get; set; }
       public object previous { get; set; }
       public int total { get; set; }
      }

      public class ImageUrls
      {
       public string large { get; set; }
       public string px_128x128 { get; set; }
       public string px_480mw { get; set; }
       public string medium { get; set; }
       public string small { get; set; }
      }

      public class FavoritedCount
      {
       public int @private { get; set; }
       public int @public { get; set; }
      }

      public class Stats
      {
       public int commented_count { get; set; }
       public FavoritedCount favorited_count { get; set; }
       public int score { get; set; }
       public int scored_count { get; set; }
       public int views_count { get; set; }
      }

      public class ProfileImageUrls
      {
       public string px_50x50 { get; set; }
      }

      public class User
      {
       public string account { get; set; }
       public int id { get; set; }
       public bool is_follower { get; set; }
       public bool is_following { get; set; }
       public bool is_friend { get; set; }
       public object is_premium { get; set; }
       public string name { get; set; }
       public object profile { get; set; }
       public ProfileImageUrls profile_image_urls { get; set; }
       public object stats { get; set; }
      }

      public class Response
      {
       public string age_limit { get; set; }
       public string book_style { get; set; }
       public string caption { get; set; }
       public object content_type { get; set; }
       public string created_time { get; set; }
       public int favorite_id { get; set; }
       public int height { get; set; }
       public int id { get; set; }
       public ImageUrls image_urls { get; set; }
       public bool is_liked { get; set; }
       public bool is_manga { get; set; }
       public object metadata { get; set; }
       public int page_count { get; set; }
       public int publicity { get; set; }
       public string reuploaded_time { get; set; }
       public Stats stats { get; set; }
       public List<string> tags { get; set; }
       public string title { get; set; }
       public List<string> tools { get; set; }
       public string type { get; set; }
       public User user { get; set; }
       public int width { get; set; }
      }

      public int count { get; set; }
      public Pagination pagination { get; set; }
      public List<Response> response { get; set; }
      public string status { get; set; }
     }



    APIリクエスト

     static Pixiv api_get(string api_str, string param)
     {
      string query = param;

      HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://public-api.secure.pixiv.net/v1/" + api_str + ".json" + query);
      req.Method = "GET";
      req.ContentType = "application/x-www-form-urlencoded";
      req.Referer = "http://spapi.pixiv.net/";
      req.UserAgent = "PixivIOSApp/5.1.1";
      req.Headers.Add("Authorization", "Bearer " + token);

      req.CookieContainer = new CookieContainer();
      req.CookieContainer.Add(new Uri("https://public-api.secure.pixiv.net"), new Cookie("PHPSESSID", sessid));

      WebResponse res = req.GetResponse();
      Stream resStream = res.GetResponseStream();
      StreamReader sr = new StreamReader(resStream, enc);
      string json = sr.ReadToEnd();

      Pixiv resp;
      resp = JsonConvert.DeserializeObject<Pixiv>(json);

      return resp;
     }


    タグ検索

    static Pixiv search(string search_tag, int page)
    {
     string param =
     "?q=" + search_tag +
     "&mode=tag&types=illustration,manga,ugoira&order=desc&sort=date&period=all" +
     "&page=" + page +
     "&per_page=25&image_sizes=px_128x128,px_480mw,large";

     return api_get("search/works", param);
    }


    イラスト詳細(タグ、閲覧数等)
    Pixiv illust_works = api_get("works/" + r.id, "?profile_image_sizes=px_170x170,px_50x50&image_sizes=px_128x128,small,medium,large,px_480mw&include_stats=true");

    foreach (var il in illust_works.response)
    {
    Console.WriteLine(il.title);
    Console.WriteLine(il.id);
    Console.WriteLine(il.caption);
    }



    teiheを新APIに対応しました(申し訳程度の宣伝)
    http://teihe.zeriyoshi.com/
  • 広告
  • またPixivAPIの仕様が変わった(2015/05/12追記)

    2014-09-24 20:37