我试图在PHP中创建一个Authorization标头,我尝试过的每次尝试都会导致错误请求,我不知道它是我的方法还是格式化。
我从API获得的文档标题需要采用以下格式:
POST https://api.URL.com/api/access/authtoken/
HEADERS {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
,
"Authorization": "Basic 8fqchs8hsafhjhc8392ch8evhdv
dvf4239gy0wNVSDVHSDJVJWd209qfhznznc932fyzIHFEOIGH
CNFCaFWFh83hfwehvljv9fbueqgf89ahwaoihOHOIHBVjeh890
owev98ewgvw209fyqnf0fmf9fm0snfa098nfw0q09fmevm9eqZ
HF89FHWE=="
}
DATA: {
"grant_type": "password",
"username": "APIUSERNAME",
"password": "password"
}
PHP的最新尝试我一直在使用stream_context_create和file_get_contents
代码片段采用以下格式。
$api_url = 'https://api.URL.com/api/access/authtoken/';
$AuthHeader = array(
'http'=>array(
'method'=>"POST",
'HEADERS'=>"Accept: application/json" .
"Content-Type: application/x-www-form-urlencoded".
"Authorization: Basic " . base64_encode("$ClientID:$ClientSecret")),
'content'=>array(
'DATA'=>"grant_type:password".
"username:USERNAME".
"password:PASSWORD" )
);
$context = stream_context_create($AuthHeader);
$result = file_get_contents($api_url, false, $context);
是我以错误的方式创建标头或格式错误的方式。 API文档不是最好的,我得到的响应没有给出任何失败的指示。任何帮助将不胜感激。
对于HTTP stream context options,它是header
,而不是HEADERS
。它还接受数组,以便更轻松地进行多标头规范。
内容似乎是x-www-form-urlencoded
,所以你需要用http_build_query()编码
结合:
$api_url = 'https://api.URL.com/api/access/authtoken/';
$AuthHeader = array(
'http' => array(
'method' => "POST",
'header' => array(
"Accept: application/json",
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Basic " . base64_encode("$ClientID:$ClientSecret")
),
'content' => http_build_query(array(
"grant_type" => "password",
"username" => "USERNAME", // to be replaced with actual username value
"password" => "PASSWORD" // ditto
))
)
);
$context = stream_context_create($AuthHeader);
$result = file_get_contents($api_url, false, $context);