c++ - Libcurl 身份验证问题
问题描述
我正在尝试在 C++ 中使用 libcurl 将请求发送到 url。当我使用 curl 在命令行中设置请求时,它似乎工作正常:
curl -vvv -X POST -H "Authorization: <api key here>" -H "Content-Type:application/json" "<host>" --data-binary '<json data here>'
响应开始如下:
> POST <host> HTTP/1.1
> Host: <host>
> User-Agent: curl/7.61.1
> Accept: */*
> Authorization: <api_key>
> Content-Type:application/json
> Content-Length: 80
所以我可以看到授权正在正确发送。
但是,当我尝试使用 libcurl C 库在 C++ 中做类似的事情时,我没有注意到请求标头前面的“>”:
代码:
struct curl_slist *chunk = NULL;
chunk = curl_slist_append(chunk, "Authorization: <api_key>");
chunk = curl_slist_append(chunk, "Content-Type:application/json");
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_URL, "<host>");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "<json>");
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
回复:
> POST <host> HTTP/1.1
Host: <host>
Accept: */*
Authentication: <api_key>
Content-Type:application/json
Content-Length: 97
所以我什至不确定主机是否正确处理或接收了标头。
有任何想法吗?
我得到以下回复:
{
"message": "No authorization header given",
"code": 401
}
解决方案
在您的命令行详细输出中,标题名为“授权:”。在您的 libcurl vebose 输出中,它的“身份验证:”。授权!=身份验证?
详细输出:
它只是命令行和 libcurl 之间的详细输出格式不同。标头已发送。例如 php curl 使用相同的输出格式。只有第一行有“>”,然后所有后面的标题都没有“>”。但是他们都提交了。
PHP curl 详细示例输出:
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 80 (#0)
> GET /XXX/api.php HTTP/1.1
Host: localhost
Accept: */*
Authorization: XXX
Content-Type: application/json
< HTTP/1.1 200 OK
< Date: Mon, 31 Dec 2018 20:12:51 GMT
< Server: Apache/2.4.34 (Win32) OpenSSL/1.1.0i PHP/7.2.10
< X-Powered-By: PHP/7.2.10
< Content-Length: 2390
< Content-Type: text/html; charset=UTF-8
<
* Connection #0 to host localhost left intact
推荐阅读
- arrays - Ruby:继续循环遍历一个固定长度的数组,每次迭代的每个元素都加 1
- java - 使用 SWIG 将字节数组转换为 C 结构
- javascript - 无法将 JavaScript 文件错误导入 html
- javascript - 根据字符串将具有多个页面的多页pdf拆分为单个pdf并使用该字符串python保存
- javascript - ReactJS + styled-components 动态大小的下拉菜单在 Safari 中不起作用
- neo4j - 启用 SSL 配置问题
- presto - 忽略字符串中的数值,Presto
- java - 构建 SOAP XML Web 服务,将数据存储到 DB 并将结果响应给客户端
- python - 通过名称而不是 ip 访问 django 主页
- angular - 无法绑定到“值”,因为它不是“p-galleria”的已知属性