访问API时,如何在PHP中使用CURL处理301(永久移动)错误? [英] How can I use CURL in PHP to handle a 301 (Moved Permanently) error when accessing an API?
问题描述
我必须使用GET请求访问API,但结果是:
I have to access an API using a GET request but the result is:
301永久移动.
301 Moved Permanently.
这是我的代码:
$curl = curl_init();
$url="https://xxx.yyy.com/zzz/v1.0";
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer sadhuUasjhda"
),
));
$result = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
print_r($result);exit;
我已阅读到可以通过添加 CURLOPT_POSTREDIR
来解决此问题,但这仅在使用POST时有效.
I've read that this problem can be solve by adding CURLOPT_POSTREDIR
, but that's only worked when I used POST.
我尝试使用 CURLOPT_FOLLOWLOCATION
,但遇到了另一个问题,结果就像
I've tried to use CURLOPT_FOLLOWLOCATION
but I get a different problem, the result is like
CURL错误#:SSL证书问题:无法获取本地颁发者证书.
CURL Error #:SSL certificate problem: unable to get local issuer certificate.
仅供参考,我正在使用Windows和XAMPP.然后,我尝试按照此 post ,但结果仍然相同.
FYI, I'm using Windows and XAMPP. And then I tried following instructions on this post but the result is still the same.
推荐答案
感谢Rendy Eko Prastiyo,解决方案是将CURLOPT_SSL_VERIFYPEER设置为false,并将CURLOPT_FOLLOWLOCATION设置为true,因此代码为
thanks to Rendy Eko Prastiyo, the solution is add CURLOPT_SSL_VERIFYPEER set to false and CURLOPT_FOLLOWLOCATION set to true, so the code is
$curl = curl_init();
$url="https://xxx.yyy.com/zzz/v1.0";
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HTTPHEADER => array(
"authorization: Bearer sadhuUasjhda"
),
));
$result = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
print_r($result);exit;
这篇关于访问API时,如何在PHP中使用CURL处理301(永久移动)错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!