我正在用PHP构建一个REST web服务客户端,目前我正在使用curl向服务发出请求。

我如何使用curl进行身份验证(http基本)请求?我必须自己添加标题吗?


当前回答

与SOAP不同,REST不是一个标准化的协议,因此拥有一个“REST客户端”有点困难。但是,由于大多数基于rest的服务使用HTTP作为其底层协议,因此您应该能够使用任何HTTP库。除了cURL, PHP还通过PEAR提供了以下功能:

HTTP_Request2

这所取代

HTTP_Request

一个他们如何做HTTP基本认证的例子

// This will set credentials for basic auth
$request = new HTTP_Request2('http://user:password@www.example.com/secret/');

也支持文摘认证

// This will set credentials for Digest auth
$request->setAuth('user', 'password', HTTP_Request2::AUTH_DIGEST);

其他回答

如果授权类型是基本认证,并且发布的数据是json,那么这样做

<?php

$data = array("username" => "test"); // data u want to post                                                                   
$data_string = json_encode($data);                                                                                   
 $api_key = "your_api_key";   
 $password = "xxxxxx";                                                                                                                 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "https://xxxxxxxxxxxxxxxxxxxxxxx");    
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");  
curl_setopt($ch, CURLOPT_POST, true);                                                                   
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     
curl_setopt($ch, CURLOPT_USERPWD, $api_key.':'.$password);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(   
    'Accept: application/json',
    'Content-Type: application/json')                                                           
);             

if(curl_exec($ch) === false)
{
    echo 'Curl error: ' . curl_error($ch);
}                                                                                                      
$errors = curl_error($ch);                                                                                                            
$result = curl_exec($ch);
$returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);  
echo $returnCode;
var_dump($errors);
print_r(json_decode($result, true));

对于那些不想使用curl的人:

//url
$url = 'some_url'; 

//Credentials
$client_id  = "";
$client_pass= ""; 

//HTTP options
$opts = array('http' =>
    array(
        'method'    => 'POST',
        'header'    => array ('Content-type: application/json', 'Authorization: Basic '.base64_encode("$client_id:$client_pass")),
        'content' => "some_content"
    )
);

//Do request
$context = stream_context_create($opts);
$json = file_get_contents($url, false, $context);

$result = json_decode($json, true);
if(json_last_error() != JSON_ERROR_NONE){
    return null;
}

print_r($result);

Michael Dowling的《Guzzle》便是一个不错的选择。除了优雅的接口、异步调用和符合PSR,它还使REST调用的身份验证头非常简单:

// Create a client with a base URL
$client = new GuzzleHttp\Client(['base_url' => 'http://myservices.io']);

// Send a request to http://myservices.io/status with basic authentication
$response = $client->get('/status', ['auth' => ['username', 'password']]);

去看医生。

你只需要指定CURLOPT_HTTPAUTH和CURLOPT_USERPWD选项:

$curlHandler = curl_init();

$userName = 'postman';
$password = 'password';

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/basic-auth',
    CURLOPT_RETURNTRANSFER => true,

    CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
    CURLOPT_USERPWD => $userName . ':' . $password,
]);

$response = curl_exec($curlHandler);
curl_close($curlHandler);

或者指定头文件:

$curlSecondHandler = curl_init();

curl_setopt_array($curlSecondHandler, [
    CURLOPT_URL => 'https://postman-echo.com/basic-auth',
    CURLOPT_RETURNTRANSFER => true,

    CURLOPT_HTTPHEADER => [
        'Authorization: Basic ' . base64_encode($userName . ':' . $password)
    ],
]);

$response = curl_exec($curlSecondHandler);
curl_close($curlSecondHandler);

狂饮的例子:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$userName = 'postman';
$password = 'password';

$httpClient = new Client();

$response = $httpClient->get(
    'https://postman-echo.com/basic-auth',
    [
        RequestOptions::AUTH => [$userName, $password]
    ]
);

print_r($response->getBody()->getContents());

看到https://github.com/andriichuk/php-curl-cookbook基本认证

与SOAP不同,REST不是一个标准化的协议,因此拥有一个“REST客户端”有点困难。但是,由于大多数基于rest的服务使用HTTP作为其底层协议,因此您应该能够使用任何HTTP库。除了cURL, PHP还通过PEAR提供了以下功能:

HTTP_Request2

这所取代

HTTP_Request

一个他们如何做HTTP基本认证的例子

// This will set credentials for basic auth
$request = new HTTP_Request2('http://user:password@www.example.com/secret/');

也支持文摘认证

// This will set credentials for Digest auth
$request->setAuth('user', 'password', HTTP_Request2::AUTH_DIGEST);