2016-11-09 64 views
0

我有下面的脚本,想知道为什么我收到错误:PHP:未能打开流:HTTP请求失败

failed to open stream: HTTP request failed! HTTP/1.1 401 Authorization Required 

Base64编码值的格式为username:password和是正确的。 API文档给的例子为:

Authorization: Basic 
QWxhZGRpbjpvcGVuIHNlc2FtZQ== 

例如,如果用户代理使用阿拉丁作为用户名和芝麻开门作为密码,则该字段被形成为上面在HTTP报头

<?php 
    $postData = array(
     'primaryContact' => array('id' => 1), 
     'subject' => 'Something not working' 
    ); 

    $context = stream_context_create(array(
     'http' => array(
      'method' => 'POST', 
      'header' => "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=\r\nContent-Type: application/json", 
      'content' => json_encode($postData) 
     ) 
    )); 

    // Send the request 
    $response = file_get_contents('http://127.0.0.1/', FALSE, $context); 

    // Check for errors 
    if($response === FALSE){ 
     die('Error'); 
    } 

    // Decode the response 
    $responseData = json_decode($response, TRUE); 

    // Print the date from the response 
    echo $responseData; 
    ?> 

任何想法?

+0

什么是你想连接?它应该留在本地主机上吗? – Hespen

回答

1

经过测试,您的代码有效。我认为它是服务器。 ATLEAST再次检查服务器的用户名和密码(你的base64编码是正确的)

我测试了:IIS 7.5的网站有基本身份验证设置(HTTP 401挑战赛) (IIS上这意味着我可以用我的Windows服务器凭据)

将$ http_response_headers添加到您的错误行以获取更多信息。

// Check for errors 
if($response === FALSE){ 
    var_dump($http_response_header); 
    die('Error'); 
} 
+0

将\ r \ n添加到最后,因为之前的评论建议由于某种原因将其固定 – pee2pee

相关问题