UbuntuでcURL+RapidJSONを使いC++からapiを叩く

環境

ライブラリの設定

libcurlのインストール

libcurlとはcURLC言語から使えるようにしたライブラリ。Ubuntuならapt-getで簡単にインストールできる

$ sudo apt-get update
$ sudo apt-get install curl libcurl3 libcurl3-dev

RapidJSONのインストール

RapidJSONとはC言語からJSONを扱うライブラリ。Rapidとあるようにパフォーマンス重視のライブラリ。

これもUbuntuならapt-getで簡単にインストールできる

$ sudo apt-get update
$ sudo apt-get install rapidjson-dev

使い方

libcurl

GoogleにGETでリクエストしてそれを表示するだけ

//test.cpp
#include <iostream>
#include <curl/curl.h>
int main(void){
     CURL *curl;
     CURLcode res;
     curl = curl_easy_init();
     if(curl) {
          curl_easy_setopt(curl, CURLOPT_URL, "https://google.co.jp");
          res = curl_easy_perform(curl);
          if(res != CURLE_OK)
               fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
          curl_easy_cleanup(curl);
     }
    return 0;
}

コンパイルするときは[-lcurl]オプションをつける

$  g++ test.cpp -lcurl
# ./a.out
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="https://www.google.co.jp/">here</A>.
</BODY></HTML>

libcurlとRapidJSON

JSON-POSTの場合

変数に代入したいときはcallback関数を用意してあげる

これはチュウニズムネットにPOSTしてレートを取得するもの

//レスポンスデータ
{
    "userId": 2038082304583461, 
    "userInfo": {
        "characterFileName": "img/0ec6bc2a17e68e8d.png", 
        "characterLevel": 14, 
        "friendCount": 0, 
        "highestRating": 1386, 
        "level": 49, 
        "playCount": 393, 
        "playerRating": 1385, 
        "point": 569100, 
        "reincarnationNum": 0, 
        "totalPoint": 867000, 
        "trophyName": "ちぇえええええええええええええええええん", 
        "trophyType": 2, 
        "userName": "NIS", 
        "webLimitDate": "2016-08-05 04:00:00.0"
    }
}
//chunithm.cpp
#include <iostream>
#include <curl/curl.h>
#include <string>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/filewritestream.h"

size_t callbackWrite(char *ptr, size_t size, size_t nmemb, std::string *stream)
{
  int dataLength = size * nmemb;
  stream->append(ptr, dataLength);
  return dataLength;
}
std::string curl_JSON_POST(std::string post_data,std::string url){

  CURL *curl;
  CURLcode ret;
  curl = curl_easy_init();
  std::string chunk;
  /*エラー処理*/
  if (curl == NULL) {
    std::cerr << "curl_easy_init() failed" << std::endl;
    return "error";
  }

  curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data.c_str());
  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callbackWrite);
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunk);
  ret = curl_easy_perform(curl);
  curl_easy_cleanup(curl);

  /*エラー処理*/
  if (ret != CURLE_OK) {
    std::cerr << "curl_easy_perform() failed." << std::endl;
    return "error";
  }
  return chunk;
}
std::string rate_get(std::string userid){
  std::string url = "https://chunithm-net.com/ChuniNet/GetUserInfoApi";
  std::string post_data = "{\"userId\":\"";
  post_data += userid;
  post_data += "\",\"friendCode\":0,\"fileLevel\":1}";

  std::string data = curl_JSON_POST(post_data,url);
  return data;
}
int main(){
  int rate;
  std::string userid;
  std::cout<<"userID : ";
  std::cin>>userid;
  rapidjson::Document document,doc;
  std::string data = rate_get(userid);
  if(document.Parse(data.c_str()).HasParseError() == false){
     rapidjson::Value& a = document["userInfo"];
     std::cout<<"rate:"<<(double)(a["playerRating"].GetInt())/100<<std::endl;
  }else{
     std::cout<<"error"<<std::endl;
  }
  return 0;
}
$ g++ chunithm.cpp -lcurl
$ ./a.out
userID : 2038082304583461
rate:13.85