我正在嘗試向https://api.powerbike.pl/發送 cURL 請求以登錄并獲取 XML,但我得到的只是
HTTP/1.1 100 Continue
HTTP/1.1 401 Unauthorized
這是我嘗試過的
$username = 'username';
$password = 'password';
$usernamePassword = 'Basic '.$username.':'.$password;
$basic = base64_encode($usernamePassword);
$loginUrl = 'https://api.powerbike.pl/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $loginUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"content-type: application/xml; charset=UTF-8",
"Authorization: $basic"
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'https://api.powerbike.pl/xml/product/categories');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HEADER, true);
$content = curl_exec($ch);
curl_close($ch);
有人可以告訴我我做錯了什么嗎?
uj5u.com熱心網友回復:
洗掉這個:
$username = 'username';
$password = 'password';
$usernamePassword = 'Basic '.$username.':'.$password;
$basic = base64_encode($usernamePassword);
$loginUrl = 'https://api.powerbike.pl/';
嘗試以下選項:
curl 將執行 base64 編碼并添加content-type:basic標頭
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD,"$username:$password");
洗掉此標頭:
"Authorization: $basic"
這可能有效"content-type: application/xml; charset=UTF-8"
您也可以嘗試"content-type: application/json; charset=UTF-8"
內容型別沒有指定任何關于您收到的內容的內容,只指定您正在發送的內容。
那就是告訴服務器您的請求是 XML 格式的。它不是。
$basic 不正確。你可以使用"$username:$password".
不要使用它,因為它需要 GET
curl_setopt($ch, CURLOPT_POST, 1);
不要使用這個:
curl_setopt($ch, CURLOPT_HEADER, true);
這將在您的$content. 你不希望出現這種情況。
我試過了,請求頭看起來是正確的。
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.powerbike.pl/xml/product/categories');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
echo $response;
echo "\n\n\nheader out: \n" . curl_getinfo($ch,CURLINFO_HEADER_OUT);
請求標頭如下所示:
GET /xml/product/categories HTTP/1.1
Host: api.powerbike.pl
Authorization: Basic cGF0cmljazphc3dkO2twZmdqaQ==
Accept: */*
Content-Type: application/xml
對于您的最終版本,這應該可以正常作業:
$header = [];
$header[] = 'Content-Type: application/xml';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.powerbike.pl/xml/product/categories');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$response = curl_exec($ch);
echo $response;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/527159.html
標籤:php卷曲
