libcurlでjsonを取得したい(C++)

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
lp6m

libcurlでjsonを取得したい(C++)

#1

投稿記事 by lp6m » 12年前

libcurlを使って(http://2048.semantics3.com/hi/start/json)のjsonを取得したいのですが、方法がわかりません。
いろいろと検索をかけてみてかいてみたのが以下のコードです.
環境はMacで,g++のバージョンはApple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)です.
g++ -libcurl main.cppでコンパイルは通りますが、実行すると空白の一行が出力されるだけになってしまいます。

どうかよろしくお願いします。

コード:

#include <string> 
#include <iostream> 
#include <curl/curl.h> 

using namespace std;

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

int main()
{
        CURL *curl;
        CURLcode ret;

        curl = curl_easy_init();
        string chunk;

        if (curl == NULL) {
                cerr << "curl_easy_init() failed" << endl;
                return 1;
        }

        curl_easy_setopt(curl, CURLOPT_URL, "http://2048.semantics3.com/hi/start/json");
        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) {
                cerr << "curl_easy_perform() failed." << endl;
                return 1;
        }

        cout << chunk << endl;

        return 0;
}
aaaaa

lp6m

Re: libcurlでjsonを取得したい(C++)

#2

投稿記事 by lp6m » 12年前

申し訳ございません、自己解決しました。

コード:

#include <string> 
#include <iostream> 
#include <curl/curl.h> 

using namespace std;
static char* errorBuffer;
static string buffer;

static int writer(char *data, size_t size, size_t nmemb, string *buffer)  
{
    int result = 0;
    if (buffer != NULL) {  
        buffer->append(data, size * nmemb);  
        result = size * nmemb;  
    }  
    return result;  
}

int main(){
    CURL *curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
        curl_easy_setopt(curl, CURLOPT_URL, "http://2048.semantics3.com/hi/start/json");
        curl_easy_setopt(curl, CURLOPT_HEADER, 0);
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);  

        CURLcode result = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
       /* if (result == CURLE_OK) {
            CCLog("curl ok! %s", buffer.c_str());
        } else {
            CCLog("curl error! %s", errorBuffer);
        }*/
    }
    printf("%s\n",buffer.c_str());
}

閉鎖

“C言語何でも質問掲示板” へ戻る