summaryrefslogtreecommitdiff
path: root/libtmdb/httpClient.cpp
blob: 93fdd76d703082a3a155e61b4a6b10def4d11ec6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "httpClient.h"
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <curl/curl.h>
#include <tmdb-api.h>

namespace TMDb {
	HttpClient::HttpClient(const std::string & bu, const std::string & k) :
		BaseURL(bu),
		ApiKey(k)
	{
	}

	void
	HttpClient::packParams(boost::format &)
	{
	}

	void
	HttpClient::appendQueryParameters(std::string & path, const Parameters::value_type & nvp) const
	{
		path += nvp.first;
		path += "=";
		auto ev = curl_easy_escape(NULL, nvp.second.value->c_str(), nvp.second.value->size());
		path += ev;
		curl_free(ev);
	}

	void
	HttpClient::appendQueryParameters(std::string & path, const Parameters & parameters) const
	{
		path += "?";	
		appendQueryParameters(path, { "apikey", ApiKey });
		BOOST_FOREACH(const auto & nvp, parameters) {
			if (nvp.second.value) {
				path += "&";	
				appendQueryParameters(path, nvp);
			}
		}
	}

	static size_t
	appendString(void * contents, size_t size, size_t nmemb, void * userp)
	{
		auto data = static_cast<Glib::ustring *>(userp);
		data->append(static_cast<const char *>(contents), size * nmemb);
		return size * nmemb;
	}

	json::Value
	HttpClient::FetchJson(const std::string & path) const
	{
		Glib::ustring jsonData;

		struct curl_slist *headers = NULL;
    curl_slist_append(headers, "Accept: application/json");

		CURL * curl_handle = curl_easy_init();
		curl_easy_setopt(curl_handle, CURLOPT_URL, path.c_str());
		curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, appendString);
		curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&jsonData);
		curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
    curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, headers); 
		CURLcode res = curl_easy_perform(curl_handle);

		long http_code = 0;
		curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &http_code);
		curl_easy_cleanup(curl_handle);
		if (res != CURLE_OK) {
			throw TMDb::HttpException(http_code);
		}

		Glib::ustring::const_iterator itr = jsonData.begin();
		return json::parseValue(itr);
	}
}