"basic_string::_M_construct null not valid" while using cpprest library - c++

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.

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 print http message in beast 1.7

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.

c++ error saving to file using stream

I'm doing some code where i redirect the output to a file, but i get error using the fstream, ostream, streambuf(). It says that
-"fstream" is ambiguous
-"ostream" is ambiguous
-class "std::basic_ostream>" has no member "streambuf"
-class "std::shared_ptr" has no member "close"
I already search it for includes, installed the lastest version of the casablanca's rest api, ... and i still get those erros.. its missing some include?
Here is the code
#include <sstream>
#include <iostream>
#include <fstream>
#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;
//Method
auto fileStream = std::make_shared<std::ostream>();
// Open stream to output file.
pplx::task<void> requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile) //Error here on the fstrea and ostream
{
*fileStream = outFile;
// Create http_client to send the request.
http_client client(U("http://localhost:53213"));
// 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()); //Error here on streambuf
})
// Close the file stream.
.then([=](size_t)
{
return fileStream.close(); //Error on 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());
}
-"fstream" is ambiguous
-"ostream" is ambiguous
-class "std::basic_ostream>" has no member "streambuf"
You are clashing std:: and casablanca's concurrency::streams namespaces, either make sure they are never pulled in with using in one file or use concurrency::streams explicitly
-class "std::shared_ptr" has no member "close"
but it does not! use -> on your fileStream
EDIT: I think your code is nothing but slightly modified version of official sample, you can just double check that you got it right
I had a similar problem, and indeed it's all to do with the namespace declaration & usage.
The comments above told only half the story.
This is what I ended up with for that application & it works:-
(using VS2019)
//using namespace std;
using namespace concurrency::streams;
stringstreambuf buffer;
auto fileStream = std::make_shared();
pplx::task requestTask = fstream::open_ostream( U("results.html")).then([=](ostream outFile)
{
*fileStream = outFile;
etc . . .

log4cxx: try/catch wont work on DOMConfigurator::configure

Well, I just wrote a simple logger program with log4cxx lib, It is working fine so far, but then I realized the exception handling doesnt work as I expected:
#include <iostream>
#include <log4cxx/logger.h>
#include <log4cxx/xml/domconfigurator.h>
#include <log4cxx/helpers/exception.h>
using namespace std;
using namespace log4cxx;
using namespace log4cxx::xml;
using namespace log4cxx::helpers;
int main(int argc, char *argv[])
{
/* some code here ... */
try
{
DOMConfigurator::configure("/path/to/logcfg.xml");
}
catch (Exception&)
{
cout << "error: problem in reading log config file" << endl;
/* here I want to free up some objects! */
exit(EXIT_FAILURE);
}
}
So, now lets say the logcfg.xml does not exist, the program will print out this message and exit:
log4cxx: Could not open file [/wrong/path/to/logcfg.xml].
Which seems to me, it never reached my exception handler, but raised and handled in library itself. Could you please tell me what is proper way to handle such case ?
Thanks

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