cURLppメモ
レスポンスヘッダを一緒に出力する場合はオプションをtrueにする
new curlpp::options::Header(true)
2chの板一覧情報をcurlppで取得するときの例。かなりすっきりと書けると思う。
相変わらずwxWidgets混じりのC++なんで、単純にコピーしただけではコンパイルできないかも。参考程度に…
// ヘッダの作成 std::list<std::string> headers; headers.push_back("Accept-Encoding: gzip"); headers.push_back("Host: menu.2ch.net"); headers.push_back("Accept: "); headers.push_back("Referer: http://menu.2ch.net/"); headers.push_back("Accept-Language: ja"); headers.push_back("User-Agent: Monazilla/1.00"); wxString server = wxT("menu.2ch.net"); wxString path = wxT("/bbsmenu.html"); const std::string url = std::string(server.mb_str()) + std::string(path.mb_str()); try { // 保存先を決める curlpp::Cleanup myCleanup; curlpp::Easy myRequest; myRequest.setOpt(new curlpp::options::Url(url)); myRequest.setOpt(new curlpp::options::HttpHeader(headers)); myRequest.setOpt(new curlpp::options::Timeout(5)); myRequest.setOpt(new curlpp::options::Verbose(true)); myRequest.setOpt(new curlpp::options::Header(true)); std::ofstream ofs(outputPath.mb_str() , std::ios::out | std::ios::trunc | std::ios::binary ); curlpp::options::WriteStream ws(&ofs); myRequest.setOpt(ws); myRequest.perform(); } catch (curlpp::RuntimeError &e) { *m_logCtrl << wxString(e.what(), wxConvUTF8) << wxString(outputPath.c_str(), wxConvUTF8) << wxT("\n"); } catch (curlpp::LogicError &e) { *m_logCtrl << wxString(e.what(), wxConvUTF8) << wxString(outputPath.c_str(), wxConvUTF8) << wxT("\n"); }
追記:レスポンスヘッダを出力する場合
このサイトを参考にしました。ありがとうございます。
curlpp を使ってみる - GET 編 - 私の日常
こんな感じでファンクタを設定する
// ヘッダー用ファンクタを設定する myRequest.setOpt(new curlpp::options::HeaderFunction(curlpp::types::WriteFunctionFunctor(this, &HogeHoge::writeMemoryCallback)));
ファンクタの中身
size_t HogeHoge::writeMemoryCallback( char *ptr, size_t size, size_t nmemb ){ size_t realsize = size * nmemb; //buf.append( static_cast<const char *>(ptr), realsize ); // 文字列をメンバ変数に格納(m_headerTest == wxString) m_headerTest.Append(wxString::FromUTF8(static_cast<const char *>(ptr), realsize)); return realsize; }
ここでのm_headerTestの型はwxStringである。要はcurlppが通信して取得した情報は「( char *ptr, size_t size, size_t nmemb )」で回ってくるので、それを変換して好きなようにすれば良いわけだ。
std::stringに格納する場合 「std::string.append( static_cast
wxStringに格納する場合 「wxString::.Append(wxString::FromUTF8(static_cast
ヘッダ出力機能はcurlpp::options::Headerにfalseを入れていても仕様出来るので安心だ
myRequest.setOpt(new curlpp::options::Header(false));
結局第4引数は使えないのだろうか。
追記
MinGWでcurlppがビルドできなかったのでソースを改変した。開発者にメッセージを送った。
Modify buildconfig.h for MinGW build · c4602d4 · Hiroyuki-Nagata/curlpp · GitHub