我在 Python 中有以下代码运行良好(可以访问):
import requests
username = 'user'
password = 'pass'
r = requests.get('https://internalwebsite/list', auth=(username, password))
j = r.json()
我如何用 PHP 编写它?
我尝试过类似的方法,但到目前为止没有成功:
$postvars = "username=user&password=pass";
$url = "https://internalwebsite/list";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1); //0 for a get request
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
print "curl response is:" . $response;
curl_close ($ch);
常规 cURL 命令也能正常工作(有响应):
curl -u 'user:pass' https://internalwebsite/list
谢谢。
请您参考如下方法:
我相信您应该使用 CURLOPT_USERPWD,而不是为这个特定用例提交 postvars(基于您对我之前的解决方案的评论)
$url = "https://internalwebsite/list";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_USERPWD, "myusername:mypassword");
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
print "curl response is:" . $response;
curl_close ($ch);
