首页 > 解决方案 > 来自 cURL API 的意外响应

问题描述

在使用 cURL 发送 API 请求时,我绝对是个初学者。

我正在尝试获取访问令牌。当我用 Reqbin 测试我的请求时,一切似乎都很好:

endpoint -> https://example.com/oauth/token
method -> POST
content type -> JSON
content:
{
    "grant_type": "password",
    "client_id": 8,
    "client_secret": "myclientsecret",
    "username": "test@email.com",
    "password": "pass",
    "scope": "*"
 }

当我发送我的请求时,我得到了预期的结果:

status -> 200 (OK)
content:
{
"token_type": "Bearer",
"expires_in": 172800,
"access_token": "my_access_token",
"refresh_token": "my_refresh_token"
}

但是,当我尝试使用 cURL 时,我得到了意外的响应。这是我的 PHP 代码:

<?php

$url = "https://example.com/oauth/token";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$headers = array(
   "Content-Type: application/json",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

$data = <<<DATA
{
        "grant_type": "password",
        "client_id": 8,
        "client_secret": "myclientsecret",
        "username": "test@email.com",
        "password": "pass",
        "scope": "*"
        }
DATA;

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

$resp = curl_exec($curl);
curl_close($curl);
var_dump($resp);

?>

这是 $resp 内容:

string(238) "<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="https://www.example.com/oauth/token">here</a>.</p>
</body></html>

我究竟做错了什么?我无法摆脱这个错误!谢谢!

标签: phpjsonrestphp-curl

解决方案


推荐阅读