HTTP Request using Google API Client Library for C++ - c++

I am trying to send an HTTP GET Request using Google API Client Library for C++ using the use case examples mentioned at http://google.github.io/google-api-cpp-client/latest/guide/making_http_requests.html.
Here's my program:
#include "googleapis/client/data/data_reader.h"
#include "googleapis/client/transport/http_request.h"
#include "googleapis/client/transport/http_response.h"
#include "googleapis/client/transport/http_transport.h"
#include "googleapis/client/transport/curl_http_transport.h"
#include "googleapis/base/scoped_ptr.h"
#include "googleapis/base/mutex.h"
#include <curl/curl.h>
#include <glog/logging.h>
#include "googleapis/util/status.h"
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace googleapis;
using namespace std;
using googleapis::client::HttpRequest;
using googleapis::client::HttpRequestState;
using googleapis::client::HttpResponse;
using googleapis::client::HttpTransport;
using googleapis::client::HttpTransportLayerConf;
using googleapis::client::HttpTransportOptions;
void IllustrateGet(const char* url, HttpTransport* transport) {
scoped_ptr<HttpRequest> request(
transport->NewHttpRequest(HttpRequest::GET));
request->set_url(url);
util::Status status = request->Execute();
if (!status.ok())
cerr << status.error_message();
}
int main(){
string url = "http://www.google.com/cloudprint";
scoped_ptr<HttpTransport> transport;
IllustrateGet(url, transport);
return 0;
}
In main(), when I try to invoke the IllustrateGet function, I get an invalid argument exception. Could some one help me understand what does HttpTransport do in order to send an HTTP GET Request?

Call IllustrateGet(url.c_str(), transport);

Related

I don't understand why my stoi says it is not declared when it supposedly is [duplicate]

my question is pretty simple but I can't seem to find it out.
I want to know what libary to include when using stoi. I was using atoi and it works fine with
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
but I get "stoi not declared" when I run with stoi. Thanks
You need to #include <string> and use a compiler that understands C++11. Minimal example:
#include <string>
#include <cassert>
int main()
{
std::string example = "1234";
int i = std::stoi(example);
assert(i == 1234);
return 0;
}
Compile, for example, with g++ -std=c++11.

JsonCpp can't find file when I use get_current_dir_name()

I am trying to parse a json file within my program:
#include <jsoncpp/json/value.h>
#include <jsoncpp/json/json.h>
#include <unistd.h>
#include <stdio.h>
int main(){
std::string plan { get_current_dir_name() };
plan += "directory/file.json";
read_json(plan); // A function that reads a json file using jsoncpp
}
Output:
Error: Json File not found!
However when I manually write the entire path:
#include <jsoncpp/json/value.h>
#include <jsoncpp/json/json.h>
#include <unistd.h>
#include <stdio.h>
int main(){
std::string plan { entire_file_path };
read_json(plan); // A function that reads a json file using jsoncpp
}
Output:
File found and read!
I thought maybe there is a spelling mistake but when I use std::cout on both of the paths, there is not a single difference. I'm not sure what is causing this issue.
Using std::filesystem built-in to C++17:
namespace fs = std::filesystem;
fs::path path = fs::current_path() / "directory" / "file.json";
read_json(path.string());

AWS C++ SDK Produces "closing connection 0" message on ShutdownAPI()

Example code:
#include <iostream>
#include <aws/core/Aws.h>
#include <aws/s3/S3Client.h>
#include <aws/s3/model/ListObjectsRequest.h>
#include <aws/s3/model/ListObjectsResult.h>
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using Aws::S3::S3Client;
using Aws::S3::Model::Object;
using Aws::S3::Model::ListObjectsOutcome;
using Aws::S3::Model::ListObjectsRequest;
using Aws::S3::Model::ListObjectsResult;
int main(int argc, char **argv) {
Aws::SDKOptions options;
Aws::InitAPI(options);
ListObjectsRequest request;
request.SetBucket("MyBucket");
ListObjectsOutcome outcome = client.ListObjects(request);
Aws::ShutdownAPI(options);
}
When the S3Client drops out of scope, I get this output:
* Closing connection 0
I think this is coming out of libcurl, but because I don't have a direct handle to curl, I don't have a direct way of managing it using the libcurl way.
Am I don't something wrong? Is there a way to suppress this message?

Mongodb c++ regex query

How to query MongoDB database using regex in c++.
mongo-cxx-driver-r3.1.1
hear is include
#include <cstdlib>
#include <iostream>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <cstdint>
#include <vector>
#include <mongocxx/stdx.hpp>
#include <bson.h>
#include <conio.h>
#include <sstream>
#include <stdio.h>
#include <string>
#include <bsoncxx/types.hpp>
#include <mongocxx/exception/exception.hpp>
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::builder::stream::open_document;
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;
here is what I have tried.
void MyClass::on_querybtn_clicked()
{
auto collection = conn["TestDB"]["fdevices"];
bsoncxx::types::b_regex::b_regex();//i am lost here dont know how to use it
auto cursor = collection.find({});
for (auto doc : cursor) {
QString qstr = QString::fromStdString(bsoncxx::to_json(doc));
QJsonDocument docum = QJsonDocument::fromJson(qstr.toUtf8());
QJsonObject object = docum.object();
QString call = object["Data"].toString();
ui.mqttList->addItem(call);
}
}
Previously I build a software using Java now I am trying to build same software in Qt c++, I am new to c++.
Here is query code that I used in java for Query.
DBObject query = new BasicDBObject();
Pattern regex = Pattern.compile("^14-09-2017");
query.put("Data", regex);
here is how my data look like.
Database image
Use some builders and make the document, providing the string input for the pattern:
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;
auto cursor = collection.find(make_document(
kvp("Data", bsoncxx::types::b_regex{"^14-09-2017"})
));
A bit easier to read than stream builder IMHO, but the basic premise is there. Still a string for input, much like Pattern.compile()
I've tried several approaches but finally I came up with the most straightforward one. I build a query as a json and then convert is to bson using bsoncxx::from_json function.
a working piece of code looks like:
mongocxx::instance instance{};
mongocxx::uri uri("mongodb://localhost:27017");
mongocxx::client *m_c = new mongocxx::client(uri);
std::string query = "{\"name.firstName\": {\"$options\": \"i\",\"$regex\": \"^pattern\"}}";
bsoncxx::builder::stream::document doc;
//this one to define q not inside try catch block.
bsoncxx::document::value q(doc.view());
try{
q = bsoncxx::from_json(query);
}catch (bsoncxx::exception &e){
std::cerr<<"error: "<<e.code()<<" "<<e.what();
return;
}
mongocxx::options::find opt;
mongocxx::cursor cursor = m_c->database("db_name").collection("collection_name").find( std::move(q), opt);
An important thing here is that I could not use q as bsoncxx::document::view.
Because a value for this view is created inside try - catch block, till the time
when the control flow came to the find function bsoncxx::document::view q was always empty. So I had to use bsoncxx::document::value q and move semantics in the find function.
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;
auto cursor = collection.find(make_document(kvp("field",make_document(kvp("$regex":"pattern"),kvp("$options","i"))));
Refer To Official

C++ REST SDK Casablanca Client.request

I want to write a little c++ program that sends a request to a server an get some data. I found the C++ Rest-SDK and decided to use it. I searched on different websites for code-examples but many of them doesn't work an shows syntax errors. What i got now is that code but the client.request method is skipped. The program never jumps in. Hope someone can realise the problem and maybe explain what i have to change.
#include <Windows.h>
#include <iostream>
#include <sstream>
#include <string>
#include "cpprest/containerstream.h"
#include "cpprest/filestream.h"
#include "cpprest/http_client.h"
#include "cpprest/json.h"
#include "cpprest/producerconsumerstream.h"
#include "cpprest/http_client.h"
#include <string.h>
#include <conio.h>
using namespace std;
using namespace web;
using namespace web::json;
using namespace web::http;
using namespace web::http::client;
using namespace utility;
using namespace utility::conversions;
int main() {
http_client client(L"http://httpbin.org/ip");
client.request(methods::GET).then([](http_response response)
{
if(response.status_code() == status_codes::OK)
{
auto body = response.extract_string().get();
std::wcout << body;
getch();
}
});
return 0;
}
It is possible that the main thread is terminated before the "request" task completed, so you cannot see any console outputs. I suggest you to call the task "wait()" function after ".then", like in the answer on their site
Your program runs off the end of main and terminates. You need to add wait after the then call:
client.request(methods::GET).then([](http_response response)
{
// ...
}).wait();
this code is working :
// ConsoleApplication1.cpp : Defines the entry point for the console application.
#include "StdAfx.h"
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
using namespace utility; // Common utilities like string conversions
using namespace web; // Common features like URIs.
using namespace web::http; // Common HTTP functionality
using namespace web::http::client; // HTTP client features
using namespace concurrency::streams; // Asynchronous streams
int main(int argc, char* argv[])
{
// Make the request and asynchronously process the response.
http_client client(L"http://localhost:8082/TPJAXRS/Test/test");
client.request(methods::GET).then([](http_response response){
if(response.status_code() == status_codes::OK){
auto body = response.extract_string().get();
std::wcout << body<< std::endl;
}});
std::cout << "Hello world!" << std::endl;
system("PAUSE");
return 0;
}
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include <cpprest/http_listener.h> // HTTP server
#include <cpprest/json.h> // JSON library
#include <cpprest/uri.h> // URI library
#include <cpprest/ws_client.h> // WebSocket client
#include <cpprest/containerstream.h> // Async streams backed by STL containers
#include <cpprest/interopstream.h> // Bridges for integrating Async streams with STL and WinRT streams
#include <cpprest/rawptrstream.h> // Async streams backed by raw pointer to memory
#include <cpprest/producerconsumerstream.h> // Async streams for producer consumer scenarios
using namespace utility; // Common utilities like string conversions
using namespace web; // Common features like URIs.
using namespace web::http; // Common HTTP functionality
using namespace web::http::client; // HTTP client features
using namespace concurrency::streams; // Asynchronous streams
using namespace web::http::experimental::listener; // HTTP server
using namespace web::experimental::web_sockets::client; // WebSockets client
using namespace web::json; // JSON library
int main(int argc, char* argv[])
{
auto fileStream = std::make_shared<ostream>();
// Open stream to output file.
pplx::task<void> requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile)
{
*fileStream = outFile;
// Create http_client to send the request.
http_client client(U("http://www.bing.com/"));
// Build request URI and start the request.
uri_builder builder(U("/search"));
builder.append_query(U("q"), U("cpprestsdk github"));
return client.request(methods::GET, builder.to_string());
})
// Handle response headers arriving.
.then([=](http_response response)
{
printf("Received response status code:%u\n", response.status_code());
// Write response body into the file.
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("Error exception:%s\n", e.what());
}
return 0;
}
This is for setting in HTTP request
link for HTTP tutorial for further information go through this tutorial