首页 > 解决方案 > 如何使用 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
}

标签: poco-libraries

解决方案


首先,您需要像这样创建一个 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);

希望它有所帮助或指向正确的方向。


推荐阅读