简体   繁体   English

错误401,使用PHP中的curl访问REST API

[英]Error 401 using curl in PHP to access REST API

I am trying to execute a curl command that I can execute successfully in the terminal but it fails in PHP script with the following error: 我正在尝试执行可以在终端中成功执行的curl命令,但在PHP脚本中失败,并出现以下错误:

HTTP/1.1 401 Unauthorized Access-Control-Allow-Origin: * Access-Control-Request-Method: * Cache-Control: no-cache Content-Type: application/json; HTTP / 1.1 401未经授权的访问控制允许来源:*访问控制请求方法:*缓存控制:无缓存内容类型:application / json; charset=utf-8 Date: Mon, 06 Feb 2012 00:38:56 GMT Server: nginx/1.0.4 Set-Cookie: _parse_session=XXXXXX; charset = utf-8日期:2012年2月6日星期一00:38:56 GMT服务器:nginx / 1.0.4 Set-Cookie:_parse_session = XXXXXX; domain=.parse.com; domain = .parse.com; path=/; 路径= /; expires=Sun, 06-Feb-2022 00:38:56 GMT; expires = Sun,2022年2月6日00:38:56 GMT; HttpOnly Status: 401 Unauthorized WWW-Authenticate: Basic realm="Parse" X-Runtime: 0.002486 X-UA-Compatible: IE=Edge,chrome=1 Content-Length: 24 Connection: keep-alive {"error":"unauthorized"} HttpOnly状态:401未经授权WWW-Authenticate:基本领域=“ Parse” X运行时:0.002486 X-UA-Compatible:IE = Edge,chrome = 1内容长度:24连接:keep-alive {“ error”:“未经授权“}

This is the command executed in terminal that executes successfully: 这是在终端中成功执行的命令:

curl -H "Accept: application/json" -H "X-Parse-Application-Id: XXXXXXX" -H "X-Parse-REST-API-Key: XXXXXXXXX" -X GET "https://api.parse.com/1/classes/XXXXXX" curl -H“接受:application / json” -H“ X-Parse-Application-Id:XXXXXXX” -H“ X-Parse-REST-API-Key:XXXXXXXXX” -X GET“ https://api.parse。 com / 1 / classes / XXXXXX“

This is the PHP code: 这是PHP代码:

$fields = array('Accept: '=>'application/json',
            'X-Parse-Application-Id:' => 'XXXXX',
            'X-Parse-REST-API-Key:' => 'XXXXX');

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.parse.com/1/classes/XXXX');

curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_HEADER, $fields);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt(CURLOPT_USERPWD, 'XXXXXX');

$result = curl_exec($ch);
curl_close($ch);

The interesting note is that when executed in the terminal authentication info is not required. 有趣的是,在终端中执行时,不需要身份验证信息。

Help will be appreciated. 帮助将不胜感激。

Thanks 谢谢

Your header fields shouldn't have the : in the array defnition: 你的头字段不应该有:在阵列defnition:

'X-Parse-REST-API-Key:' => 'XXXXX');
                     ^---remove these

That makes the : part of the field name, so you're actually sending: 这使得:成为字段名称的一部分,因此您实际上是在发送:

X-Parse-REST-API-Key:: XXXXX
                    ^^---note the doubled colons

标头是使用CURLOPT_HTTPHEADER设置的,而不是使用CURLOPT_HEADER设置的,该期望值是布尔值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM