How to print http message in beast 1.7 - c++

I can't print base of http request, since migration to beast 1.70.0
I previously done that by:
std::cerr << ctx.res.base()
but currently looks like operator isn't overloaded, how to do it in 1.70.0?
problem can be reproduced with following code: (mind that beast 1.70.0 should be used)
#include <boost/beast/http.hpp>
#include <boost/beast/http/write.hpp>
#include <iostream>
using namespace boost::beast;
http::response<http::string_body> res {};
int main()
{
std::cout << res.base();
}

This is a bug in Boost 1.70 which is fixed in version 1.71. A work-around is to define the macro BOOST_BEAST_ALLOW_DEPRECATED for your build.

Related

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?

How to get hh:mm:ss.uuuuuu timestamp in c++?

I'm looking to print hh:mm:ss.uuuuuu timestamps in C++. It seems like I need to use the chrono library and std::chrono::use high_resolution_clock::now()?
I'm unsure how to proceed from here however.
This is easily accomplished with this C++20 chrono preview library which works with C++11/14/17:
#include "date/date.h"
#include <chrono>
#include <iostream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
cout << format("%T", floor<microseconds>(system_clock::now())) << '\n';
}
Just output for me:
19:31:54.033196
This will port to C++20 by:
Drop #include "date/date.h"
Drop using namespace date;
Change "%T" to "{:%T}"
This is a header-only, open-source library.
The output is UTC. If you need local time, that is available too, but the library is not header-only. It is at the same link and would be used like this:
#include "date/tz.h"
#include <chrono>
#include <iostream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
zoned_time zt{current_zone(), floor<microseconds>(system_clock::now()))};
cout << format("%T", zt) << '\n';
}
The above syntax uses C++17. If you're using C++11 or 14 change zoned_time to zoned_time<microseconds>.
Some installation is required for the tz.h library.

"basic_string::_M_construct null not valid" while using cpprest library

I'm starting working with C++ and it's cpprestsdk. I've searched a lot and also tried to copy valid examples from the internet but nothing works. Can anyone help me to deal with this error? This code compiles, but it's throwing the exception "basic_string::_M_construct null not valid" at auto response = client.request(request).get();
#include <cpprest/filestream.h>
#include <cpprest/http_client.h>
#include <cpprest/uri.h>
#include <cpprest/json.h>
using namespace utility;
using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace concurrency::streams;
...
try {
auto client = client::http_client{ U("https://jsonplaceholder.typicode.com/") };
auto request = http_request{ methods::POST };
request.set_request_uri(U("/posts"));
// Exception is thrown here. If i'll comment everything under this line, code works.
auto response = client.request(request).get();
logprintf("Logged: %d", response.status_code());
}
catch (std::exception& e) {
logprintf("ERROR %s", e.what());
}
logprintf is just a wrapper for printf. It's working fine.

Make boost http client

I am new to boost library so my question is probably not the first one in this forum but I couldn't find a similar case.
Currently I am trying to implement a simple HTTP client which calls REST API.
I inspired my self from the example given on the boost's web site: HTTP client with boost
The example is clear enough for a newbie like me but I would like to make the client to be able to execute multiple requests one by one because the example is a one shot: the client sends a GET request to the server, than it receives the response and after that the io_service.run() returns.
So my question is what I need to use from boost in way to make my client always waiting for new requests to send.
I read something about a io_service::work but I am not sure if it is the right way.
Does anybody have done something similar to the client I am trying to make?
Thanks in advance !
Best regard,
Anton
I do not know if asynchronous version is a must, so I would recommend you to give a try to synchronous version, since it's easier to follow the execution path:
/*
Compile with
g++ -lpthread -lboost_system -lboost_thread -ohttp http.cpp
*/
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <boost/asio.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/thread.hpp>
using std::cout;
using std::endl;
using std::vector;
using std::string;
using boost::asio::ip::tcp;
using boost::asio::ip::address;
using boost::asio::io_service;
using boost::asio::buffer;
using boost::system::error_code;
using boost::system::system_error;
int main()
{
try
{
unsigned int PORT = 80;
const string HOST = "216.58.214.238";
const string HTTP_REQUEST = "GET /index.html HTTP/1.0\n\n";
io_service ios;
tcp::endpoint ip_port(address::from_string(HOST), PORT);
while (true)
{
tcp::socket client(ios);
client.connect(ip_port);
const int BUFLEN = 1024;
vector<char> buf(BUFLEN);
client.send(buffer(HTTP_REQUEST, HTTP_REQUEST.size()));
error_code error;
int len = client.receive(buffer(buf, BUFLEN), 0, error);
cout << "main(): buf.data()=";
cout.write(buf.data(), len);
cout << endl;
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
}
}
catch (system_error& exc)
{
cout << "main(): exc.what()=" << exc.what() << endl;
}
return EXIT_SUCCESS;
}
The socket is created each time within the loop because Google (it's IP address is used) closes the connection after each request (status 302 is returned).
In some other cases, HTTP connection does not have to be closed by a server, so socket can be reused.

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