使用 PHP curl 出现 411 错误
我有以下代码:
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $this->credentials);
if ($action == 'post') {
curl_setopt($ch, CURLOPT_HTTPHEADER, array ("Content-Type: application/json"));
curl_setopt($ch, CURLOPT_POST, 1);
if(isset($params)){
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
}
}
我基本上试图模仿以下内容:
curl --user $APPLICATION_ID:$MASTER_KEY \
-X POST \
-H "Content-Type: application/json" \
-d '{"score": 1337, "playerName": "Sean Plott", "cheatMode": false }' \
https://api.somewebsite.com/1/classes/GameScore
到目前为止 $params 是一个数组,不确定这是否正确..我应该对 $params 进行 json_encode 吗?如何消除 411 错误?
I have the following code:
curl_setopt($ch, CURLOPT_URL, $request);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $this->credentials);
if ($action == 'post') {
curl_setopt($ch, CURLOPT_HTTPHEADER, array ("Content-Type: application/json"));
curl_setopt($ch, CURLOPT_POST, 1);
if(isset($params)){
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
}
}
I am basically trying to mimic the following:
curl --user $APPLICATION_ID:$MASTER_KEY \
-X POST \
-H "Content-Type: application/json" \
-d '{"score": 1337, "playerName": "Sean Plott", "cheatMode": false }' \
https://api.somewebsite.com/1/classes/GameScore
As of now $params is an array, not sure if this is correct or not.. should I json_encode the $params? How do I get rid of the 411 error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
http_build_query
仅用于发送application/x-www-form-urlencoded
数据,而您的则不是。您的 POST 数据可能很混乱,因此您没有随请求发送Content-Length
标头。假设您的参数是这些键值对的数组,您可以使用以下内容:http_build_query
is only for sendingapplication/x-www-form-urlencoded
data, which yours isn't. Your POST data is probably messed up so you're not sending aContent-Length
header with your request. Assuming you have your params as an array of those key-value pairs, you can use the following:这应该可以解决问题:
直接传递 json 字符串即可。您的命令行版本没有为此 json 数据指定字段名,因此 PHP/curl 版本也不应该指定。
This should do the trick:
Just pass the json string in directly. Your command line version isn't specifying a fieldname for this json data, so the PHP/curl version shouldn't either.
411 长度必需 表示客户端(即您)失败指定
Content-Length
标头。由于curl会自动添加它,但如果您无法提供发布数据,则将其设置为
-1
,因此$param
可能未设置或http_build_query
没有设置返回您所期望的。如果您尝试一下,问题还会出现吗?
411 Length Required means the client (i.e. you) failed to specify a
Content-Length
header.Since curl adds it automatically, but sets it to
-1
if you fail to give post data,$param
is probably unset orhttp_build_query
does not return what you expect. If you try justdoes the problem still occur?