POCO how to send XML data? - c++

In my project,I have encountered a serious problem which program can't receive data and then crash.
these are my code :
HTTPClientSession s("x.x.x.x",8000);
HTTPRequest request(HTTPRequest::HTTP_POST);
std::ostream& send = s.sendRequest(request);
std::string body = "<a> xml </a>";
request.setContentLength( body.length() );
send << body <<std::flush;
HTTPResponse response;
std::istream& res = s.receiveResponse(response);
StreamCopier::copyStream(res, std::cout);
After I run it,when my program received data from server,it crashed and throw
Poco::Net::messageException
.Oh,my god!
I traced it into internal code of POCO , finding :
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
is my data sended property in VS2005.
At the same time ,Poco find the last letter of <!DOCTYPE is Ewhich is not a space ,so it throw the exception.
Do any one encouter the case? who can help me ?Thank you ,very much!!!!

I'm sending data almost the same way. There's just one difference in my code.
request.setContentType("text/xml; charset=utf-8");
According to the source code of the Poco library, exception 'Poco::Net::MessageException' is raised because of malformed response from http server.

Related

C++ Boost http post request [duplicate]

I've to use a C++ library for sending data to a REST-Webservice of our company.
I start with Boost and Beast and with the example given here under Code::Blocks in a Ubuntu 16.04 enviroment.
The documentation doesn't helped me in following problem:
My code is, more or less, equal to the example and I can compile and send a GET-request to my test webservice successfully.
But how can I set data inside the request (req) from this definition:
:
beast::http::request<beast::http::string_body> req;
req.method("GET");
req.target("/");
:
I tried to use some req.body.???, but code completition doesn't give me a hint about functionality (btw. don't work). I know that req.method must be changed to "POST" to send data.
Google doesn't show new example about this, only the above code is found as a example.
Someone with a hint to a code example or using about the Beast (roar). Or should I use websockets? Or only boost::asio like answered here?
Thanks in advance and excuse my bad english.
Small addition to Eliott Paris's answer:
Correct syntax for setting body is
req.body() = "name=foo";
You should add
req.prepare_payload();
after setting the body to set body size in HTTP headers.
To send data with your request you'll need to fill the body and specify the content type.
beast::http::request<beast::http::string_body> req;
req.method(beast::http::verb::post);
req.target("/");
If you want to send "key=value" as a "x-www-form-urlencoded" pair:
req.set(beast::http::field::content_type, "application/x-www-form-urlencoded");
req.body() = "name=foo";
Or raw data:
req.set(beast::http::field::content_type, "text/plain");
req.body() = "Some raw data";

Postman Error: Value is not a valid byteString

I am trying to invoke a POST web service via Postman and I am getting the following error.
Error while sending request: Failed to execute setRequestHeader on
XMLHttpRequest: Value is not a valid ByteString.
Request Headers
X-PW-AccessToken:{{api_token}}
X-PW-Application:developer_api
X-PW-UserEmail:{{api_email}}
Content-Type:application/json
Request Body
{
"page_size": 25
}
Can anyone tell me why I am getting this error, and how can I get rid of this?
I think Http protocol's header can only post ByteString (what is ByteString? I think it is ASCII).
So if you have other char, for example, 汉字. if you put '汉字' add to Http Header the error 'Value is not a valid ByteString' happen!
Solove: You can use the encodeURI function to encode the String in the client, and then, You can use URLdecode.decode()(java) to decode the header information in the server.

Poco HTTPClientSession adding headers to HTTPRequest

Try to send POST method to server using JSON. But, server also requires model, platform and platform version as headers to request. How can I add these headers to HTTPRequest. At Postman, I can add it in Headers tab. Eg. Model: Redmi 4 Platform: android. Feel free to edit to make it clear to others.
Below there is my code who HTTPRequest creates:
Poco::JSON::Object obj;
obj.set("login", "log123");
obj.set("password","pas123");
Poco::Net::HTTPClientSession session("http://hostAddress",
80); //giving host name and port number
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST,
"http://requestAddress","1.1"); //initializing request body
Poco::Net::HTTPResponse response;
std::stringstream ss;
obj.stringify(ss);
request.setContentType("application/json");
request.setContentLength(ss.str().length());
std::ostream& oStream = session.sendRequest(request);// sends request, returns open stream
obj.stringify(oStream);
std::istream& iStream = session.receiveResponse(response);
I tried to find some information at https://pocoproject.org/docs/Poco.Net.HTTPRequest.html. https://pocoproject.org/docs/Poco.Net.HTTPMessage.html. But without results.
There is one solution. It can help to others.
request.add("string:key","string:value") //In order to add headers to request.
Eg:
request.add("X-Make","Xiaomi");
request.add("X-Model","Redmi 4");
request.add("X-Platform","android");
request.add("X-Platform-Version","6.0.1");
It works for me.

Error with Flex HTTPService and Django, even though POST is successful

(This is the first time I've done this actually.)
<mx:HTTPService id="post_update" method="POST" result="{Dumper.info('bye')}"/>
The result handler above is just for debugging purposes, but its never hit, even though what I'm uploading via POST...
post_update.url = getPath(parentDocument.url)+"update";
post_update.send(new_sel);
...is received and handled successfully by my Django view:
def wc_post(request) :
request.session['wc'] = request.POST
return http.HttpResponse("<ok/>", mimetype="text/xml")
As far as what I'm sending back from Django, I'm following the guidelines here:
Sending Images From Flex to a Server
I just don't want it to generate an error on the Flex side considering Django is actually receiving and processing the data. Any help appreciated. Can't remember the text of the error in Flex at the moment.
UPDATE: new_sel (what I'm posting from Flex) is just a Flex Object, with various text fields.
UPDATE: various error messages from event.message (in fault handler):
faultCode = "Server.Error.Request"
faultString = "HTTP request error"; DSStatusCode = 500; errorID = 2032; type = "ioError"
This is more grasping at straws than answers, but do I have to send a particular type of header back from Django- the default sent by Django includes a 200 success status code, and the response I was sending of "<ok/>" with mime type of "text/xml" was following the example exactly that I provided from that other source.
And also the url I'm sending the POST to is localhost:8000/wr_view1/wr_webcube/update, and I previously successfully did a GET to localhost:8000/wr_view1/wr_webcube/webcube.xml, and despite the .xml extension in the case of GET, it was still being handled by Django (and without errors in Flex). In the case of this POST, once again, the data is actually succesfully sent and handled by Django, but Flex is returning Error 2032, which I found out can mean numerous different things including cross domain issues, but don't see how that's the case here.
Just had to return HttpResponse("ok") Didn't like it being sent as xml for some reason. So much ado about nothing I guess.

Using cpp-netlib 0.8 as a HTTP Proxy - Helpless

I am trying to use cpp-netlib in a project of mine. I simply need to create a HTTP proxy into which I can plug in some functionality later. For now, I just need to listen to requests, send request to a new site, and forward the answer of the new request to the first request.
This is the code I have so far:
std::string ip = source(request);
http::client client;
std::ostringstream url;
url << "www.example.com/image.jpg";
http::client::request clientRequest(url.str());
http::client::response clientResponse = client.get(clientRequest);
response = server::response::stock_reply(server::response::ok);
response.headers = clientResponse.headers(); //This is not possible - not correct type or something
response.content = clientResponse.body();
Results in error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::multimap<_Kty,_Ty>' (or there is no acceptable conversion)
A request to the test image I am using yields 19.4kb data in the response. If I do the same request through the above code (without header copying) I get an answer with about 4kb data, which the browser tries to show as text (default header). It does seem like an image though, even in text.
Anyone out there that is familiar with cpp-netlib-0.8? is response.content = clientResponse.body(); the correct way? How can I add the correct headers?
It's altogether too much template weirdness in cpp-netlib for me to understand it right now!
Thanks...
Instead of using:
response.content = clientResponse.body();
the correct way is:
std::string body_content = body(clientResponse);
also, you are using response as variable, while your variable is actually clientResponse
For more examples read cpp-netlib v0.8 documentation