我正在尝试连接到API,验证用户身份,然后查看用户详细信息.这是通过首先访问登录端点来完成的
http://api.example.com/login/<username>/<password>
Run Code Online (Sandbox Code Playgroud)
登录,然后查看以下内容以查看用户详细信息:
http://api.example.com/user/
Run Code Online (Sandbox Code Playgroud)
这一切都可以在Web浏览器中使用.但是,一旦我尝试使用Curl,登录工作正常,但在尝试查看用户详细信息时,我会收到401,未经授权的错误.我相信这是因为Curl没有正确保存会话cookie?有人可以指出它为什么不工作以及如何解决它?我已经尝试过搜索堆栈交换,但是,我尝试过的解决方案都没有适用于我的情况.我用来卷曲端点的代码如下所示.谢谢!
define("COOKIE_FILE", "cookie.txt");
// Login the user
$ch = curl_init('http://api.example.com/login/joe/smith');
curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
echo curl_exec ($ch);
// Read the session saved in the cookie file
echo "<br/><br/>";
$file = fopen("cookie.txt", 'r');
echo fread($file, 100000000);
echo "<br/><br/>";
// Get the users details
$ch = curl_init('http://api.example.com/user');
curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
echo curl_exec ($ch);
Run Code Online (Sandbox Code Playgroud)
此代码将输出:
HTTP/1.1 200 OK Date: Mon, 22 Oct 2012 21:23:57 …Run Code Online (Sandbox Code Playgroud)