I'm trying to communicate with some server. To get username (with permissions), I need to do something like registration: HTTP request method POST send json-like body containing {"devicetype": "devicename"}. O tried to do it with ASIO library.
asio::error_code ec;
asio::io_context context;
asio::ip::tcp::endpoint endpoint(asio::ip::make_address("ipAddress", ec), 80);
asio::ip::tcp::socket socket(context);
if (!ec)
{
std::cout << "Succesfully connected\n";
}
else
{
std::cout << "Failed to connect to address: \n" << ec.message() << std::endl;
}
if (socket.is_open())
{
std::string sRequest =
"POST /api HTTP/1.1\r\n"
"Host: ipAddress \r\n"
"Body: {\"devicetype\": \"devicename\"}"
"Connection: close\r\n\r\n";
socket.write_some(asio::buffer(sRequest.data(), sRequest.size()), ec);
/*Reading received message and getting error message from server*/
}
Error says: "invalid/missing parameters in body". The parameters are correct. The problem is probably with message formatting I am sending (sRequest). How can I specify json body to message?
Thanks for help.
What you have shown is not a properly formatted HTTP request. There is no Body header in HTTP. The JSON data needs to go after the \r\n\r\n that terminates the headers. And you need to add Content-Type and Content-Length headers so the server knows what kind of data you are posting and how large it is.
Try this instead:
std::string json = "{\"devicetype\": \"devicename\"}";
std::string sRequest =
"POST /api HTTP/1.1\r\n"
"Host: ipAddress\r\n"
"Content-Type: application/json\r\n"
"Content-Length: " + std::to_string(json.size()) + "\r\n"
"Connection: close\r\n\r\n" + json;
Related
I am trying to send a get request to acounts.google.com to be able to implement a library for C++ OAuth to learn it.
I get the following code from this post: Creating a HTTPS request using Boost Asio and OpenSSL and modified it as follow:
int main()
{
try
{
std::string request = "/o/oauth2/v2/auth";
boost::system::error_code ec;
using namespace boost::asio;
// what we need
io_service svc;
ssl::context ctx(svc, ssl::context::method::sslv23_client);
ssl::stream<ip::tcp::socket> ssock(svc, ctx);
ip::tcp::resolver resolver(svc);
auto it = resolver.resolve({ "accounts.google.com", "443" }); // https://accouts.google.com:443
boost::asio::connect(ssock.lowest_layer(), it);
ssock.handshake(ssl::stream_base::handshake_type::client);
// send request
std::string fullResuest = "GET " + request + " HTTP/1.1\r\n\r\n";
boost::asio::write(ssock, buffer(fullResuest));
// read response
std::string response;
do
{
char buf[1024];
size_t bytes_transferred = ssock.read_some(buffer(buf), ec);
if (!ec) response.append(buf, buf + bytes_transferred);
std::cout << "Response received: '" << response << "'\n"; // I add this to see what I am getting from the server, so it should not be here.
} while (!ec);
// print and exit
std::cout << "Response received: '" << response << "'\n";
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
if (std::string const * extra = boost::get_error_info<my_tag_error_info>(e))
{
std::cout << *extra << std::endl;
}
}
}
The problem that I have is as follow:
1- The results that I am getting is not what I am getting when I visit https://accounts.google.com/o/oauth2/v2/auth using a web browser. I essentially getting a message that they can not find the requested URL /o/oauth2/v2/auth
<p>The requested URL <code>/o/oauth2/v2/auth</code> was not found on this server. <ins>ThatÔÇÖs all we know.</ins>
How should I setup the GET commend so I can get the same result that I am getting with a browser?
2- The application hangs getting data from server, apparently the following loop is not right:
do
{
char buf[1024];
size_t bytes_transferred = ssock.read_some(buffer(buf), ec);
if (!ec) response.append(buf, buf + bytes_transferred);
} while (!ec);
What is the correct way of reading responce from the web server which is fast and read all data?
Edit 1
For reference based on accepted answer, I fixed the problem using the correct GET header as shown below:
// send request
std::string fullResuest = "GET " + request + " HTTP/1.1\r\n";
fullResuest+= "Host: " + server + "\r\n";
fullResuest += "Accept: */*\r\n";
fullResuest += "Connection: close\r\n\r\n";
boost::asio::write(ssock, buffer(fullResuest));
A HTTP/1.1 request must have a Host header. A simple experiment with OpenSSL will show the problem, i.e. the missing header:
$ openssl s_client -connect accounts.google.com:443
...
GET /o/oauth2/v2/auth HTTP/1.1
... The requested URL <code>/o/oauth2/v2/auth</code> was not found on this server. <ins>That’s all we know.</ins>
When adding the Host header instead we get a different response:
$ openssl s_client -connect accounts.google.com:443
...
GET /o/oauth2/v2/auth HTTP/1.1
Host: accounts.google.com
... >Required parameter is missing: response_type<
Apart from that HTTP/1.1 implicitly uses HTTP keep-alive, i.e. server and client might keep the connection open after the response is done. This means you should not read until the end of connection but should instead properly parse the HTTP header, extract the Content-length header and/or Transfer-Encoding header and behave according to their values. Or if you want it simpler use HTTP/1.0 instead.
For more information see the HTTP/1.1 standard.
Using boost-asio I prepared simple code:
asio::io_service io_service;
asio::ip::tcp::socket s(io_service);
asio::ip::tcp::resolver resolver(io_service);
asio::connect(s, resolver.resolve({ "aire.pl", "80" }));
cout << "connected" << endl;
string request = "GET http://aire.pl/ HTTP/1.1";
size_t request_length = std::strlen(request.c_str());
asio::write(s, asio::buffer(request, request_length));
cout << "packet sent" << endl;
char reply[1024];
size_t reply_length = asio::read(s, asio::buffer(reply, request_length));
std::cout << "Reply is: ";
std::cout.write(reply, reply_length);
std::cout << "\n";
Everything seems to work fine, because using tcp-dump I can see my packets that the program has sent:
But I don't have any response. The one interesting fact is that, if HTTP server is nginx it works ok! In this example, the HTTP server is Apache2. What's wrong?
It looks like you haven't sent a complete HTTP request. The GET line is followed by optional headers, followed by a blank line to indicate the end of the headers. Even if you don't want to send any headers, you need to send the blank line so that the server knows it's received the entire request.
Add \r\n\r\n to the end of your request string.
I have implemented a HTTPS client using boost::asio library, implementation went fine , yet the problem arises when I send a GET request that invokes some servlet like entity.
GET request
request_stream << "GET "<<"https://172.198.71.135:8085/jrnal_content/test?data=MFBLUQ==&iv=aHU5Rw=="<<" HTTP/1.0\r\n"
The request was successfully written from my end to the server, but the response I have been getting is 403 ("Forbidden"), later sometime I sent another GET request.
request_stream << "GET "<<"https://172.198.71.135:8085/users/Sign_in"<<" HTTP/1.0\r\n"
For which I've got 200, I really do not know what went wrong in my first request (that received 403), I am sure there is no problem with certificate and stuff,I've never implemented an HTTP client/server before,so I want to make sure whether am making a proper request call.
Please see my code below
boost::asio::io_service io_service1;
boost::asio::io_service &io_service(io_service1);
boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23);
boost::asio::ssl::context& context_=ctx;
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> socket_(io_service,context_);
int main()
{
context_.set_options(boost::asio::ssl::context::default_workarounds| boost::asio::ssl::context::no_sslv2
| boost::asio::ssl::context::single_dh_use);
context_.set_password_callback(my_password_callback);
context_.use_certificate_chain_file("SSL\\rich.crt");
context_.use_private_key_file("SSL\\rich.key", boost::asio::ssl::context::pem);
boost::asio::ssl::context ctx(boost::asio::ssl::context::sslv23);
tcp::resolver resolver_(io_service);
tcp::resolver::query query("172.198.71.135", "https");
tcp::resolver::iterator endpoint_iterator = resolver_.resolve(query);
boost::asio::connect(socket_.lowest_layer(),endpoint_iterator);
socket_.lowest_layer().set_option(tcp::no_delay(true));
socket_.set_verify_mode(boost::asio::ssl::verify_peer);
socket_.set_verify_callback(boost::bind(verify_certificate));//(boost::asio::ssl::rfc2818_verification("172.198.71.135"));
socket_.handshake(boost::asio::ssl::stream_base::client);
boost::asio::placeholders::error, boost::asio::placeholders::iterator));
string path="https://172.198.71.135:8085/jrnal_content/test?";
temp=path+"data="+data+"&"+"iv="+Iv;
boost::asio::streambuf request;
std::ostream request_stream(&request);
request_stream << "GET "+temp+" HTTP/1.0\r\n" ;
request_stream << "Host: " <<"172.198.71.135"<< "\r\n";
request_stream << "Accept: */*\r\n";
request_stream << "Connection: close\r\n\r\n";
const char* header=boost::asio::buffer_cast<const char*>(request.data());
cout<<header<<endl;
try{
boost::asio::write(socket_, request);
request_stream.clear();
t=sizeof(request);
request.consume(t);
}catch(runtime_error e)
{ ss<<e.what();
string err=ss.str();
err="";
ss.str("");
}
boost::asio::streambuf response;
try{
boost::asio::read_until(socket_, response, "\r\n");
}catch(runtime_error e)
{
ss<<e.what();
string err=ss.str();
err="";
ss.str("");
}
std::istream response_stream(&response);
std::string http_version;
response_stream >> http_version;
unsigned int status_code;
response_stream >> status_code;
cout<<status_code<<" status_code"<<endl;
std::string status_message;
std::getline(response_stream, status_message);
if (!response_stream || http_version.substr(0, 5) != "HTTPS/")
{
}
if (status_code==200)
{
ss<<ID;
string SID=ss.str();
ss.str("");
boost::asio::read_until(socket_, response, "\r\n\r\n");
response_stream.clear();
t=sizeof(response);
response.commit(t);
}
else{
Sleep(6000);
continue;
}
Sleep(7000);
}
return 0;
}
string my_password_callback(size_t t, boost::asio::ssl::context_base::password_purpose p)//std::size_t max_length,ssl::context::password_purpose purpose )
{
std::string password;
return "12345";
}
bool verify_certificate()
{
return true;
}
Thanks to sehe for the valuable suggestions he has given, So At last, I found what caused the issue.
tcp::resolver::query query("172.198.71.135", "https");
The above query gets resolved to 172.198.71.135:443 and the port NO 443 is blocked intentionally.
request_stream << "GET "<<"https://172.198.71.135:8085/jrnal_content/test?data=MFBLUQ==&iv=aHU5Rw=="<<" HTTP/1.0\r\n"
So things get changed as
tcp::resolver::query query("172.198.71.135", "https");
to
tcp::resolver::query query("172.198.71.135", "8085");
The "three-digit mess" is what's commonly referred to as "a number". In this case, the number is HTTP Status Code of the webserver's response.
If you read up on "HTTP" and perhaps even that HTTP response code, you'll find that it means Forbidden:
A web server may return a 403 Forbidden HTTP status code in response to a request from a client for a web page or resource to indicate that the server can be reached and understood the request, but refuses to take any further action. Status code 403 responses are the result of the web server being configured to deny access, for some reason, to the requested resource by the client.
Make sure to supply the required HTTP Authentication
I want to connect to an HTTPS server using boost::asio. I managed to successfully shake hands with the server, but I just can't manage to get the server to respond to my POST request.
This is the related code (I left out debugging and try-catch to save some space):
HTTPSClient::HTTPSClient()
{
ssl::context context(ssl::context::sslv23);
context.set_verify_mode(ssl::verify_peer);
context.set_default_verify_paths();
context.load_verify_file("certificate.pem");
mSSLSocket = new ssl::stream<ip::tcp::socket>(mIOService, context);
}
void HTTPSClient::SendRequest(const ptree &crPTree, const std::string cHost,
const std::string cURI)
{
tcp::resolver resolver(mIOService);
tcp::resolver::query query(cHost, "https");
resolver.async_resolve(query, boost::bind(&HTTPSClient::HandleResolve, this,
placeholders::error, placeholders::iterator, request));
}
void HTTPSClient::HandleResolve(const error_code &crError,
const iterator &criEndpoints, HTTPSRequest &rRequest)
{
async_connect(mSSLSocket->lowest_layer(), criEndpoints,
boost::bind(&HTTPSClient::HandleConnect, this, placeholders::error,
rRequest));
}
void HTTPSClient::HandleConnect(const error_code &crError, HTTPSRequest &rRequest)
{
mSSLSocket->lowest_layer().set_option(ip::tcp::no_delay(true));
mSSLSocket->set_verify_callback(ssl::rfc2818_verification(rRequest.mcHost));
mSSLSocket->handshake(ssl::stream_base::client);
// Write the json into a stringstream
std::ostringstream json;
boost::property_tree::write_json(json, rRequest.mcPTree);
std::string result;
result = json.str();
// Form the request
streambuf request;
std::ostream requestStream(&request);
requestStream << "POST " << rRequest.mcURI << " HTTP/1.1\r\n";
requestStream << "Host: " << rRequest.mcHost << "\r\n";
requestStream << "Accept: application/json\r\n";
requestStream << "Content-Type: application/json; charset=UTF-8\r\n";
requestStream << "Content-Length: " << result.length() << "\r\n";
requestStream << result << "\r\n\r\n";
write(*mSSLSocket, request);
streambuf response;
read_until(*mSSLSocket, response, "\r\n");
std::istream responseStream(&response);
}
read_until hangs until it throws the error read_until: End of file. Everything before that goes successfully, including the SSL handshake (which I just recently figured out).
I used to do everything asynchronously until I started debugging, and started trying to backtrace to the problem, to no avail. It would be awesome if someone could help me out after two painful days of debugging.
EDIT
I just realized it might be useful to add the contents of requestStream after composing the header:
POST /authenticate HTTP/1.1
Host: <hostname>
Accept: application/json
Content-Type: application/json; charset=UTF-8
Content-Length: 136
{
"username": "vijfhoek",
"password": "test123",
<other json content>
}
You need a double linefeed before the body (POST contents)
POST /authenticate HTTP/1.1
Host: <hostname>
Accept: application/json
Content-Type: application/json; charset=UTF-8
Content-Length: 136
{
"username": "vijfhoek",
"password": "test123",
<other json content>
}
Otherwise, the content will have been received by the server as header lines and the server just keeps waiting for 136 bytes of content data (also make sure that Content-Length is accurate, which it isn't in this example)
So, basically:
requestStream << "Content-Length: " << result.length() << "\r\n";
requestStream << "\r\n"; // THIS LINE ADDED
I managed to figure out what I was doing wrong. For some reason, I couldn't get boost to write data using the boost::asio::streambuf and std::ostream approach. Instead, I put the POST data in a std::string and sent it like this:
write(*mSSLSocket, boost::asio::buffer(requestString));
Which worked out fine.
I've been trying to get this to work for a couple of days however I keep getting a 400 error from the server.
Basically, what I'm trying to do is send a http POST request to a server that requires a JSON request body with a couple of properties.
These are the libs I'm currently using
UPDATED --- 7/23/13 10:00am just noticed I'm using TCP instead of HTTP not sure how much this will effect an HTTP call but i can't find any examples of clients using pure HTTP with BOOST::ASIO
#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <boost/asio.hpp>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using boost::property_tree::ptree; using boost::property_tree::read_json; using boost::property_tree::write_json;
using boost::asio::ip::tcp;
SET UP CODE
// Get a list of endpoints corresponding to the server name.
tcp::resolver resolver(io_service);
tcp::resolver::query query(part1, "http");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
// Try each endpoint until we successfully establish a connection.
tcp::socket socket(io_service);
boost::asio::connect(socket, endpoint_iterator);
// Form the request. We specify the "Connection: close" header so that the
// server will close the socket after transmitting the response. This will
// allow us to treat all data up until the EOF as the content.
boost::asio::streambuf request;
std::ostream request_stream(&request);
JSON BODY
ptree root, info;
root.put ("some value", "8");
root.put ( "message", "value value: value!");
info.put("placeholder", "value");
info.put("value", "daf!");
info.put("module", "value");
root.put_child("exception", info);
std::ostringstream buf;
write_json (buf, root, false);
std::string json = buf.str();
HEADER AND CONNECTION REQUEST
request_stream << "POST /title/ HTTP/1.1 \r\n";
request_stream << "Host:" << some_host << "\r\n";
request_stream << "User-Agent: C/1.0";
request_stream << "Content-Type: application/json; charset=utf-8 \r\n";
request_stream << json << "\r\n";
request_stream << "Accept: */*\r\n";
request_stream << "Connection: close\r\n\r\n";
// Send the request.
boost::asio::write(socket, request);
I put place holder values however if you see anything that doesn't work in my code that jumps out please let me know I have no idea why i keep getting a 400, bad request.
info about the rig
C++
WIN7
VISUAL STUDIO
Although this question is very old I would like to post this answer for users who are facing similar problem for http POST.
The server is sending you HTTP 400 means "BAD REQUEST". It is because the way you are forming your request is bit wrong.
The following is the correct way to send the POST request containing JSON data.
#include<string> //for length()
request_stream << "POST /title/ HTTP/1.1 \r\n";
request_stream << "Host:" << some_host << "\r\n";
request_stream << "User-Agent: C/1.0\r\n";
request_stream << "Content-Type: application/json; charset=utf-8 \r\n";
request_stream << "Accept: */*\r\n";
request_stream << "Content-Length: " << json.length() << "\r\n";
request_stream << "Connection: close\r\n\r\n"; //NOTE THE Double line feed
request_stream << json;
Whenever you are sending any data(json,string etc) with your POST request, make sure:
(1) Content-Length: is accurate.
(2) that you put the Data at the end of your request with a line gap.
(3) and for that (2nd point) to happen you MUST provide double line feed (i.e. \r\n\r\n) in the last header of your header request. This tells the header that HTTP request content is over and now it(server) will get the data.
If you don't do this then the server fails to understand that where the header is ending ? and where the data is beginning ? So, it keeps waiting for the promised data (it hangs).
Disclaimer: Feel free to edit for inaccuracies, if any.