我正在用PHP构建一个REST Web服务客户端,目前我正在使用curl向服务发出请求.
如何使用curl进行身份验证(http basic)请求?我必须自己添加标题吗?
你要这个:
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
Zend有一个REST客户端和zend_http_client,我确信PEAR有一些包装器.但它很容易自己做.
所以整个请求看起来像这样:
$ch = curl_init($host); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', $additionalHeaders)); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $payloadName); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $return = curl_exec($ch); curl_close($ch);
CURLOPT_USERPWD
基本上发送user:password
带有http头的字符串的base64,如下所示:
Authorization: Basic dXNlcjpwYXNzd29yZA==
所以除了CURLOPT_USERPWD
你还可以使用HTTP-Request
header选项以及下面的其他标题:
$headers = array( 'Content-Type:application/json', 'Authorization: Basic '. base64_encode("user:password") // <--- ); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
最简单和原生的方式是直接使用CURL.
这对我有用:
4> nategood..:与SOAP不同,REST不是标准化协议,因此拥有"REST客户端"有点困难.但是,由于大多数RESTful服务使用HTTP作为其底层协议,因此您应该能够使用任何HTTP库.除了cURL之外,PHP还有以下PEAR:
HTTP_Request2
取而代之的
HTTP_REQUEST
他们如何进行HTTP Basic Auth的示例
// This will set credentials for basic auth $request = new HTTP_Request2('http://user:password@www.example.com/secret/');还支持Digest Auth
// This will set credentials for Digest auth $request->setAuth('user', 'password', HTTP_Request2::AUTH_DIGEST);
5> 小智..:如果授权类型为“基本身份验证”,发布的数据为json,则执行此
"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));