使用PHP CURL发送POST请求时返回401错误,求排查
问题排查与修复方案
你的代码存在三个关键问题,导致返回401未授权且无数据:
1. Custom-Token格式错误
$headers里的Custom-Token值前后多了冗余逗号,这会让API无法识别有效令牌,直接触发401验证失败。
错误写法:
$headers = array('Custom-Token'=>',mycustomtoken=', 'Content-Type'=>'application/json' );
正确写法:
$headers = array('Custom-Token'=>'mycustomtoken', 'Content-Type'=>'application/json' );
2. POST数据格式不符合API要求
你把JSON字符串包装在$options数组中,再通过http_build_query转成form-urlencoded格式,但API要求直接发送JSON请求体,而非表单编码格式。这种错误的请求格式会导致API无法解析内容,同时可能间接触发授权验证失败。
错误处理逻辑:
$options=array( 'data'=>$json, ); $options_string = http_build_query($options); curl_setopt($ch, CURLOPT_POSTFIELDS, $options_string);
正确处理逻辑:直接将JSON字符串作为CURLOPT_POSTFIELDS的值,无需转换格式:
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
3. JSON字符串冗余换行(非致命但建议修复)
你的JSON字符串末尾存在多余换行,虽然多数API可兼容,但为避免潜在解析问题,建议移除:
$json = '{ "pageSize": "10", "page": "1", "types": [ "pressRelease", "blog", "news" ], "topics": [], "from": "2015-01-10T13:32:56.447Z" }';
修复后的完整代码
$headers = array('Custom-Token'=>'mycustomtoken', 'Content-Type'=>'application/json' ); $url = "https://example.com/items"; $json = '{ "pageSize": "10", "page": "1", "types": [ "pressRelease", "blog", "news" ], "topics": [], "from": "2015-01-10T13:32:56.447Z" }'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $data = curl_exec($ch); $response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($response_code == 200 || $response_code == 201) { echo $data; } else { echo $response_code; }
内容的提问来源于stack exchange,提问作者TBJ
相关产品推荐
相关产品推荐

