[英]How to replicate cURL and python's 'requests' library in PHP?
我在 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);
您需要通過curl_setopt($ch, CURLOPT_POST, 1);
啟用HTTP POST
curl_setopt($ch, CURLOPT_POST, 1);
而不是curl_setopt($ch, CURLOPT_POST, 0);
如果您使用 POST。 嘗試這個
$username = 'user';
$password = 'pass';
$url = 'https://internalwebsite/list';
//init curl
$ch = curl_init();
//Set the URL to work with
curl_setopt($ch, CURLOPT_URL, $url);
// ENABLE HTTP POST
curl_setopt($ch, CURLOPT_POST, 1);
//Set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, 'user=' . $username . '&pass=' . $password);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
print "curl response is:" . $response;
curl_close($ch);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, ( $url . '?' . $postvars ) );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$response = curl_exec($ch);
curl_close($ch);
echo "response is $response";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.