简体   繁体   English

在PHP中使用curl GET遇到麻烦

[英]Having trouble with curl GET in PHP

I'm trying to get a JSON response from a curl GET request, but have not been able to get it to work. 我正在尝试从curl GET请求获取JSON响应,但无法使其正常工作。 I've tried several examples and am just not getting anything back. 我已经尝试了几个示例,但什么都没得到。 This is what I'm trying: 这是我正在尝试的:

$Url = "http://app.whistle.com/api/dogs/132376/dailies/16955&X-Whistle-AuthToken=xxxxxxxxxxxxxxxxxxxxxxxx";

$ch = curl_init($Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo $result;

Does anyone know why this isn't working? 有人知道为什么这行不通吗?

The url returns a HTTP 401 status (not authorised). 网址返回HTTP 401状态(未授权)。 This means that the authentication failed. 这意味着身份验证失败。 You should check your authentication parameters. 您应该检查身份验证参数。 Check if you need to set username and password, or that your AuthToken is valid. 检查是否需要设置用户名和密码,或者您的AuthToken有效。

curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");

You seem to add X-Whistle-AuthToken to the URL. 您似乎将X-Whistle-AuthToken添加到URL。 First of all, that would be done, starting with ? 首先,从?开始? since it's the first parameter, not with & . 因为它是第一个参数,而不是&

Secondly since this X-Whistle-AuthToken starts with an X- I assume that it is a HTTP header that needs to be send as a HTTP header using CURL, not as a HTTP GET parameter. 其次,由于此X-Whistle-AuthTokenX-开头,因此我假定它是一个HTTP标头,需要使用CURL而不是HTTP GET参数作为HTTP标头发送。 But you have to check the corresponding documentation to make sure how the API expects your answer. 但是,您必须检查相应的文档,以确保API如何期望您的答案。

Something like this will probably work as it should: 这样的事情可能会正常工作:

$Url = "http://app.whistle.com/api/dogs/132376/dailies/16955";

$ch = curl_init($Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Whistle-AuthToken: 214cca48930110a634cfc34fe9b4ee17"));

$result = curl_exec($ch);
if ($result === false){ die(curl_error($ch)); }

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
var_dump($result);

Last but not least: 最后但并非最不重要的:

Change your AuthToken. 更改您的AuthToken。 You just leaked a private token that should probably stay private. 您只是泄露了一个可能应该保持私有状态的私有令牌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM