poco-libraries - 如何使用 POCO 库和 OAuth2 发送 Get 和 Post 请求
问题描述
我有一个本机窗口应用程序,想要访问 gitlab 服务的 API,希望使用 POCO 库和 OAuth2 使用名称和密码获取令牌,但我不知道如何使用 OAuth2 向 gitlab 发送 Get 和 Post 请求,并且使用 POCO 库,请给我一个例子。
这是需要发送和接收的数据。
使用参数向 /oauth/token 请求访问令牌 POST 请求:
{
"grant_type" : "password",
"username" : "user@example.com",
"password" : "secret"
}
然后,您将在响应中收到访问令牌:
{
"access_token": "1f0af717251950dbd4d73154fdf0a474a5c5119adad999683f5b450c460726aa",
"token_type": "bearer",
"expires_in": 7200
}
解决方案
首先,您需要像这样创建一个 HTTPRequest 对象:
Poco::Net::HTTPClientSession* session = Poco::Net::HTTPSessionFactory::defaultFactory().createClientSession(serverUri);
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, serverUri.getPathAndQuery(), Poco::Net::HTTPMessage::HTTP_1_1);
然后创建一个 HTMLForm:
Poco::Net::HTMLForm form;
form.add("grant_type", "password");
form.add("client_id", "client token");
form.add("client_secret", "client secret");
form.add("username", "user@example.com");
form.add("password", "secret");
form.prepareSubmit(request);
发送请求并将表单数据写入请求的输出流:
std::ostream& requestStream = session->sendRequest(request);
form.write(requestStream);
从会话中获取响应:
Poco::Net::HTTPResponse response;
std::istream& responseStream = session->receiveResponse(response);
std::stringstream rawJson;
Poco::StreamCopier::copyStream(responseStream, rawJson);
解析原始 JSON:
Poco::JSON::Parser parser;
Poco::JSON::Object::Ptr authObj = parser.parse(rawJson).extract<Poco::JSON::Object::Ptr>();
为下一个请求创建一个新会话并将授权标头附加到请求中:
Poco::Net::HTTPClientSession* dataSession = Poco::Net::HTTPSessionFactory::defaultFactory().createClientSession(dataUri);
Poco::Net::HTTPRequest dataRequest(Poco::Net::HTTPRequest::HTTP_GET, dataUri.getPathAndQuery(), Poco::Net::HTTPMessage::HTTP_1_1);
dataRequest.add("Authorization", "Bearer " + authObj->get("access_token"));
dataSession->sendRequest(dataRequest);
获取响应并从流中读取数据:
std::stringstream data;
Poco::Net::HTTPResponse dataResponse;
Poco::StreamCopier::copyStream(dataSession->receiveResponse(dataResponse), data);
希望它有所帮助或指向正确的方向。
推荐阅读
- sql - 反转字符串中元素的顺序
- python - 如何根据两个变量重新采样以派生均匀的类?
- closedxml - ClosedXML - 在最新版本中通过 API 返回工作簿的方法不再起作用
- data-modeling - 关系建模与规范化
- java - 使用 Jackson 读取自定义地图键
- google-cloud-automl - 似乎无法导入谷歌云顶点 AI 文本情感分析数据集
- django - 在 django-rest-framework-jwt 中缓存身份验证结果
- r - R中纵向荟萃分析的可视化
- reactjs - 如何将数据从一个组件输出到另一个组件?
- javascript - Amcharts 4 gridIntervals到json不起作用