[英]Poco::Net::HTTPClientSession json data Content-Type not received
[英]Poco library PUT method not working as expected although host, method, content-type are set correctly
我在带有Poco库的C ++中使用以下代码,该代码应在本地主机上执行PUT,其内容为{"name" : "sensorXXX", "totalLots" : 50, "occupied": 5}
string url = String("http://localhost:3000/cam1111");
URI uri(url);
HTTPClientSession session(uri.getHost(), uri.getPort());
// prepare path
string path(uri.getPathAndQuery());
if (path.empty()) path = "/";
// send request
HTTPRequest req(HTTPRequest::HTTP_PUT, path, HTTPMessage::HTTP_1_1);
req.setContentType("application/json");
string body = string("{\"name\" : \"Parking Sensor developed by aromanino\", \"totalLots\" : 50, \"occupied\": 5}");
// Set the request body
req.setContentLength( body.length() );
// sends request, returns open stream
std::ostream& os = session.sendRequest(req);
cout<<"request sent to " <<uri.getHost()<<endl;
cout<<"port "<<uri.getPort()<<endl;
cout<<"path "<<uri.getPathAndQuery()<<endl;
cout<<"body:\n"<<body<<endl;
HTTPResponse res;
cout << res.getStatus() << " " << res.getReason() << endl;
return 0;
应该将其放在NodeExpress中完成的本地中间件上。
我得到200作为回应,所以应该可以。
但是中间件正在接收某些东西(因此主机和端口是正确的),但是它没有执行我期望的终点:
router.put("/:dev", function(req, res){
//console.log(req.params.dev);
/*Check if request contains total and occupied in the body: If not reject the request.*/
var stat;
var body_resp = {"status" : "", "message" : ""};;
console.log(req.body);
....
});
并且router.all('*', ...)
也不捕获它。
相同的主机,正文,内容类型正在邮递员上按预期工作。
我应该在Poco库中设置更多内容以执行正确的PUT请求。
您实际上并没有通过HTTP请求发送正文,如:
std::ostream& os = session.sendRequest(req);
os << body;
此外,在发送带有正文的请求之后,还必须接收服务器响应-仅声明HTTPResponse对象是不够的。
HTTPResponse res;
std::istream& is = session.receiveResponse(res);
因此,完整的代码段应为:
string url = string("http://localhost:3000/cam1111");
URI uri(url);
HTTPClientSession session(uri.getHost(), uri.getPort());
string path(uri.getPathAndQuery());
if (path.empty()) path = "/";
HTTPRequest req(HTTPRequest::HTTP_PUT, path, HTTPMessage::HTTP_1_1);
req.setContentType("application/json");
string body = string("{\"name\" : \"Parking Sensor developed by aromanino\", \"totalLots\" : 50, \"occupied\": 5}");
req.setContentLength(body.length());
std::ostream& os = session.sendRequest(req);
os << body;
HTTPResponse res;
std::istream& is = session.receiveResponse(res);
cout << res.getStatus() << " " << res.getReason() << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.