我如何通过授权头使用cURL?(可在/usr/bin/curl中执行)。


当前回答

(对于那些正在寻找php-curl答案的人)

$service_url = 'https://example.com/something/something.json';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password"); //Your credentials goes here
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //IMP if the url has https and you don't want to verify source certificate

$curl_response = curl_exec($curl);
$response = json_decode($curl_response);
curl_close($curl);

var_dump($response);

其他回答

下面的方法对我很有用

curl -H "Authorization: Token xxxxxxxxxxxxxx" https://www.example.com/

注意,当你使用: curl -H "授权:token_str" http://www.example.com

token_str和Authorization必须用空格隔开,否则服务器端将无法获得HTTP_AUTHORIZATION环境。

(对于那些正在寻找php-curl答案的人)

$service_url = 'https://example.com/something/something.json';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password"); //Your credentials goes here
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //IMP if the url has https and you don't want to verify source certificate

$curl_response = curl_exec($curl);
$response = json_decode($curl_response);
curl_close($curl);

var_dump($response);

如果在调用时没有令牌,则必须进行两次调用,一次获取令牌,另一次从响应中提取令牌,请注意

Grep令牌| cut -d, -f1 | cut -d\" -f4

因为它是处理从响应中提取令牌的部分。

echo "Getting token response and extracting token"    
def token = sh (returnStdout: true, script: """
    curl -S -i -k -X POST https://www.example.com/getToken -H \"Content-Type: application/json\" -H \"Accept: application/json\" -d @requestFile.json | grep token | cut -d, -f1 | cut -d\\" -f4
""").split()

提取令牌后,您可以使用令牌进行后续调用,如下所示。

echo "Token : ${token[-1]}"       
echo "Making calls using token..."       
curl -S -i -k  -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer ${token[-1]}" https://www.example.com/api/resources 

FWIW,在Mac OS上,我发现我需要用引号包围目标url时,它包含查询参数,例如,

curl -H "Authorization: Token xxxxxxxxxxxxxx" "https://www.example.com/?param=myparam"