【发布时间】:2019-11-11 02:35:32
【问题描述】:
我正在使用 c++ pastiche rest api 库在 ubuntu linux 中制作一个 rest api。
我已经让服务器正常工作。我可以使用 php curl 将数据发布到我的服务器。服务器接收数据并可以返回数据。
问题是这样的。当我使用 curl post 发布到服务器时,它会以像 name=percy&age=34&eye_color=blue 这样的 url 编码字符串将其发送到服务器。
我需要知道如何在 C++ 中将每一个放入一个字符串中。
此外,其中一个字段也可能具有二进制数据以及普通字符串。我已经编写了解释二进制数据的代码,但目前我不知道如何从 curl post 转换字符串。
请忽略我的端口在我的 php.ini 中不同的事实。原因是我在virtualbox中运行ubuntu。
我需要从我发送的帖子中提取字符串和二进制数据。这是我不知道该怎么做。 我不确定是否需要另一个库来执行此操作
这是我的 php 代码:-
$postData = http_build_query(
array(
'dstdata' => 'hello',
'more' => 'test',
'age' => 34
)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'localhost:9999/about');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
print_r($output);
curl_close($ch);
上面的代码会生成这样的字符串dstdata=hello&more=test&age=34
这里是 c++ 服务器代码。你可以看到我在这里设置了两条路线:-
#include <pistache/router.h>
#include "pistache/endpoint.h"
#include "pistache/http.h"
#include <iostream>
using namespace Pistache;
using namespace Rest;
Rest::Router router;
void sausage(const Rest::Request& request, Http::ResponseWriter response){
std::cout << "We have contact" << std::endl;
response.send(Http::Code::Ok, "Bottoms Up\n");
}
void about(const Rest::Request& request, Http::ResponseWriter response){
std::cout << "Server Running" << std::endl;
response.send(Http::Code::Ok, request.body());
}
int main(){
Routes::Get(router,"/ready",Routes::bind(&sausage));
Routes::Post(router,"/about",Routes::bind(&about));
Pistache::Address addr(Pistache::Ipv4::any(), Pistache::Port(9080));
auto opts = Pistache::Http::Endpoint::options()
.threads(10).flags(
Pistache::Tcp::Options::ReuseAddr);
Http::Endpoint server(addr);
server.init(opts);
server.setHandler(router.handler());
server.serve();
return 0;
}
【问题讨论】:
-
如果使用正确,卷曲编码的 URL 不应与任何其他 URL 不同。我不太明白你的问题。
-
我不知道如何转换编码的字符串,以便我可以访问一个字符串。例如,我可能想将年龄放入 int 中,或者将名称放入字符串中,但我不确定如何。我发送的数组中的一个对象也可能是二进制文件,我也必须对其进行解析。