我正在尝试连接到API,对用户进行身份验证,然后查看用户详细信息。这是通过首先访问登录端点来完成的
http://api.example.com/login/<username>/<password>
登录,然后单击以下内容查看用户详细信息:
http://api.example.com/user/
所有这些都可以在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);
此代码将输出:
HTTP/1.1 200 OK Date: Mon, 22 Oct 2012 21:23:57 GMT Server: LiteSpeed Connection: close X-Powered-By: PHP/5.3.14 Set-Cookie: cfapi=f481129c9616b8f69cc36afe16466545; path=/ Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Content-Type: application/json X-Powered-By: CFWAPI 0.1a Content-Length: 46 {"status":200,"msg":"Successfully Logged In."} # Netscape HTTP Cookie File # http://curl.haxx.se/rfc/cookie_spec.html # This file was generated by libcurl! Edit at your own risk. api.example.com FALSE / FALSE 0 cfapi 94f63b07ccf7e34358c1c922341c020f HTTP/1.1 401 Unauthorized Date: Mon, 22 Oct 2012 21:23:57 GMT Server: LiteSpeed Connection: close X-Powered-By: PHP/5.3.14 Set-Cookie: cfapi=a8eb015a7c423dde95aa01579c4729a4; path=/ Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Content-Type: application/json X-Powered-By: CFWAPI 0.1a Content-Length: 49 {"status":401, "msg":"You need to login first!"}
您还需要设置该选项CURLOPT_COOKIEFILE。
CURLOPT_COOKIEFILE
手册将其描述为
包含cookie数据的文件的名称。cookie文件可以是Netscape格式,也可以是纯HTTP样式的标头转储到文件中。如果名称为空字符串,则不会加载任何cookie,但仍启用cookie处理。
由于您使用的是Cookiejar,因此最终会在请求完成时保存cookie,但是由于CURLOPT_COOKIEFILE未提供,因此cURL不会在后续请求中发送任何已保存的cookie。