如何将带有身份验证的file_get_contents url转换为cURL请求

时间:2018-04-23 05:46:06

标签: php curl file-get-contents

我有一个脚本,使用file_get_contents()

从网址获取一些内容
$auth_headers = 'Authorization: Basic '.$api_credentials."\r\n".
                    'Content-Type: application/x-www-form-urlencoded;charset=UTF-8'."\r\n";

$auth_context = stream_context_create(
        array(
            'http' => array(
                'header' => $auth_headers,
                'method' => 'POST',
                'content'=> http_build_query(array('grant_type' => 'client_credentials', )),
            )
        )
    );
$auth_response = json_decode(file_get_contents($auth_url, 0, $auth_context), true);
$auth_token = $auth_response['access_token'];    


$data_context = stream_context_create( array( 'http' => array( 'header' => 'Authorization: Bearer '.$auth_token."\r\n", ) ) );

$data = json_decode(file_get_contents($data_url.'&count='.$data_count.', 0, $data_context), true);

以上是我编写的代码并且工作正常,出于某些原因我需要将其更改为cURL请求。无法找到如何将$auth_context和所有内容添加到cURL请求中。

以下我试过cURL,

$url = $auth_url;
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);

$contents = curl_exec($ch);
if (curl_errno($ch)) {  
    echo curl_error($ch);  echo "\n";  $contents = '';
} else {  
    curl_close($ch);
}
if (!is_string($contents) || !strlen($contents)) {
    echo "Failed to get contents.";$contents = '';
}
print_r($contents);

收到“无法获取内容”错误声明。 任何人都帮我将其转换为cURL请求。

更新 我为cURL尝试了以下代码,仍然是同样的声明“无法获取内容。”

$fields = http_build_query(array('grant_type' => 'client_credentials', ));
$url = $auth_url;
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $api_key . ":" . $api_secret);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields)), $auth_headers);
//curl_setopt($ch, CURLOPT_HTTPHEADER, $auth_headers);

$contents = curl_exec($ch);
if (curl_errno($ch)) {  
    echo curl_error($ch);  echo "\n";  $contents = '';
} else {  
    curl_close($ch);
}
if (!is_string($contents) || !strlen($contents)) {
    echo "Failed to get contents.";$contents = '';
}
print_r($contents);

0 个答案:

没有答案