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 . . .
Related
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.
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.
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
I am following the basic libcurl curlcpp example below
#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
#include <string>
#include <sstream>
#include <iostream>
// RAII cleanup
curlpp::Cleanup myCleanup;
// standard request object.
curlpp::Easy myRequest;
int main(int, char**)
{
// Set the URL.
myRequest.setOpt(new curlpp::options::Url(std::string("http://www.wikipedia.com")));
// Send request and get a result.
// By default the result goes to standard output.
// Here I use a shortcut to get it in a string stream ...
std::ostringstream os;
os << myRequest.perform();
std::string asAskedInQuestion = os.str();
return 0;
}
It has been a while since I used c++ but I am sure I have used the << operator before. Am I missing an include needed to make it work?
You cannot redirect standard output like that: in order for the << operator to work, the myRequest.perform() member function needs to return its output - either as a string, or as another object for which there exists an overload of the << operator for output streams.
Since myRequest.perform() is void, you need to tell curlpp to write to your string stream by using some other mechanism. In curlpp that is done by setting a write stream option - like this:
std::ostringstream os; // Here is your output stream
curlpp::options::WriteStream ws(&os);
myRequest.setOpt(ws); // Give it to your request
myRequest.perform(); // This will output to os
I want to using Poco::Net::StreamSocket socket to download file from internet.
I need a source template.
Anyone help me!
This code worked for me:
#include "Poco/URIStreamOpener.h"
#include "Poco/StreamCopier.h"
#include "Poco/Path.h"
#include "Poco/URI.h"
#include "Poco/Exception.h"
#include "Poco/Net/HTTPStreamFactory.h"
#include "Poco/Net/FTPStreamFactory.h"
#include <memory>
#include <iostream>
using Poco::URIStreamOpener;
using Poco::StreamCopier;
using Poco::Path;
using Poco::URI;
using Poco::Exception;
using Poco::Net::HTTPStreamFactory;
using Poco::Net::FTPStreamFactory;
int main(int argc, char** argv)
{
HTTPStreamFactory::registerFactory(); // Must register the HTTP factory to stream using HTTP
FTPStreamFactory::registerFactory(); // Must register the FTP factory to stream using FTP
string url = "http://somefile.mp3";
string filePath = "C:\\somefile.mp3";
// Create and open a file stream
std::ofstream fileStream;
fileStream.open(filePath, ios::out | ios::trunc | ios::binary);
// Create the URI from the URL to the file.
URI uri(url);
// Open the stream and copy the data to the file.
std::auto_ptr<std::istream> pStr(URIStreamOpener::defaultOpener().open(uri));
StreamCopier::copyStream(*pStr.get(), fileStream);
fileStream.close();
}
A lot of the above came from the example code found here.
Have a look on page 11 of the Poco network slides, it should help to get you started.