【发布时间】:2019-12-05 11:22:14
【问题描述】:
我正在尝试在浏览器中显示来自 PHP POST 请求的响应字符串。如果我跑:
<?php
$project_id = "abcdefgh";
$session_id = "123456789";
$url = "https://dialogflow.googleapis.com/v2/projects/".$project_id."/agent/sessions/".$session_id.":detectIntent";
$query = '{
"query_input": {
"text": {
"text": "Test input",
"language_code": "en-US"
}
}
}';
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $query);
//So that curl_exec returns the contents of the cURL; rather than echoing it
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
//execute post
$result = curl_exec($ch);
echo $result;
curl_close($ch);
?>
在 VSCode 中,我得到以下响应(这是预期行为):
{
"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
但是,如果我在 Chrome 中导航到我的 WAMP 服务器上运行的 index.php 文件,我会看到一个空白屏幕。我可以回显其他字符串,例如:
我什至可以直接复制响应,并将响应作为字符串在浏览器中回显。它似乎不适用于发布请求(也许这是一个时间问题?)。这可能是 WAMP 配置/权限问题,但我觉得问题可能出在其他地方。感谢您的帮助!
【问题讨论】:
-
日志是怎么说的?
-
您要恢复错误消息吗?
-
在本地执行您的代码,可以得到您所说的预期结果。 “我得到一个空白屏幕。” - 您是否启用了适当的 PHP 错误报告?如果没有,请先这样做。
-
您必须进行身份验证并告诉 curl 以 JSON 格式发送
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Authorization: Bearer add_token_here_')); -
使用 var_dump($result) 或使用 print_r($result);
标签: php curl post wamp wampserver