簡體   English   中英

盡管正確設置了主機,方法和內容類型,但Poco庫的PUT方法無法按預期工作

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM