I am following Pixabay API documentation to retrieve/download images. I don't have a lot of understanding of URI/REST/HTTP workings but I was able to follow some documentation and get boilerplate code:
int main()
{
auto fileStream = std::make_shared<ostream>();
//Open stream for output file
pplx::task<void> requestTask = fstream::open_ostream("results.html")
.then([=](ostream outFile) {
http_client client("https://pixabay.com/");
uri_builder builder("/api/");
builder.append_query("key", "xxxxxxx-xxxxxx-xxxxxxx");
builder.append_query("q", "yellow%20flowers");
builder.append_query("image_type", "photo");
std::cout << builder.to_string() << std::endl;
return client.request(methods::GET, builder.to_string()); })
// Handle the response headers arriving
.then([=](http_response response) {
printf("Received response status code: %u\n", response.status_code());
return response.body().read_to_end(fileStream->streambuf()); })
// Close the file stream.
.then([=](size_t) {
return fileStream->close(); });
// Wait for all the outstanding I/O to complete and handle any exceptions
try {
requestTask.wait();
}
catch (const std::exception &e) {
printf("Exception: %s\n", e.what());
}
return 0;
}
Problem : This code always gives me status code 301. If I directly run https://pixabay.com/api/?key=xxxxxxx-xxxxxx-xxxxxxx&q=yellow+flowers&image_type=photo&pretty=true this link in the browser, I am getting the JSON data back. I am not sure if I am able to build this URI correctly through URI builder using the above code.
Some variation of the code that I tried involves commenting out query parameter q
, removing/adding /
from http_client/uri_builder
but none of that worked.
Please help me understand what is the correct way of getting this done.
Thanks!