2

我正在尝试从我自己的应用程序访问服务器及其数据。要登录,我需要用户名和密码以及我拥有的证书。我的问题是我显然发送此信息是错误的,因为我一直收到 401。我应该能够在此页面上,在登录后从该服务器获取一些 HAL+JSON 数据。它从前一页发布了一个字段,并应将其提交给服务器以获取数据。

这是我的代码:

$username = 'foo';
$password = 'bar';
$auth_token = $username . '-' . $password;

$url = 'https://data.service.com'.$_POST['url'].'?callback=?';
$ch = curl_init($url); 
/* Upon receiving the right certificate 
*  I should have a cookie with this information. 
*/
$data_string = array('cert_url' => 'https://data.service.com/cert/2364o872ogfglsgw8ogiblsjy');    
/* That hash at the end corresponds to the Public Key ID 
*  in the certificate. No idea how to retrieve this, 
*  or if I need to do it to login
*/
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);      
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HEADER, true);     
curl_setopt($ch, CURLOPT_HTTPHEADER, array(   
      'Accept: application/javascript',
      'Access-Control-Allow-Origin: *',                                                                       
      'Content-Type: application/javascript',
      "Authorization: Basic " . base64_encode($username.":".$password)
   ));  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);  
curl_setopt($ch, CURLOPT_FAILONERROR, true);  
curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, true);    
curl_setopt($ch, CURLOPT_VERBOSE, true);                                                                                                            
$result = curl_exec($ch);  
if(curl_exec($ch) === false){
      echo 'Curl error: ' . curl_error($ch);
      print_r(error_get_last());
} else {
      echo 'Operation completed without any errors';
curl_close($ch);
$response = json_decode($result, true); ?>
4

1 回答 1

1

看看http://www.php.net/manual/ru/function.curl-setopt.php#98164

尽量不要使用

"Authorization: Basic " . base64_encode($username.":".$password)

或者让 curl 选择一种身份验证方法,试试

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); 

对于 curl 不喜欢远程服务器上的 ssl 证书的情况,请尝试以下操作:

curl_setopt( $ch , CURLOPT_SSL_VERIFYPEER , false ); 
curl_setopt( $ch , CURLOPT_SSL_VERIFYHOST , false );

PS你确定 CURLOPT_RETURNTRANSFER 在你的情况下应该是假的吗?

于 2013-04-04T07:47:41.997 回答