php - 返回状态为400时使用phps file_get_contents获取服务器发送的内容
问题描述
我正在使用 phpsfile_get_contents
连接我的 API 服务器。当服务器返回 200 状态时它运行良好(它从 api 服务器返回内容)。问题是当 api 服务器返回 400 状态时。如果 api 服务器返回 400 状态,该函数只返回 FALSE(不是内容)。
这是我从$http_response_header得到的
[ "HTTP\/1.1 400 Bad Request",
"Server: nginx\/1.16.1",
"Date: Fri, 06 Nov 2020 05:39:09 GMT",
"Content-Type: application\/json",
"Content-Length: 117",
"Connection: close",
"Strict-Transport-Security: max-age=31536000; includeSubDomains; preload",
"Access-Control-Allow-Origin: *",
"Access-Control-Expose-Headers: Content-Length,Content-Type,Date,Server,Connection" ]
现在我的问题是,当状态为 400 时,如何获取从API 服务器发送的内容?
解决方案
您可以使用 curl 而不是file_get_contents
因为它对错误处理有更好的支持:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "{url}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
// handle any other code than 200
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
// your handling code
print_r($output);
}
curl_close($ch);
推荐阅读
- c++ - 如何降低我的(非正统的)基于 Qt5/QML 的软件的内存使用量?
- functional-programming - 调用函数和函数式编程有什么区别
- c# - C# 编译表达式以创建 T 的新实例并将值从 T 的另一个实例复制到其属性
- c# - 如何修复 'IHasInputDevices 已过时。使用 Actions 或 ActionsBuilder 类通过 Selenium 模拟鼠标和键盘输入警告
- node.js - 其他 IPS 无法访问 NodeJS 项目
- swift - 转换到视图控制器时强制解开 UIImageView 的 nil 可选
- jquery - 为 DT 闪亮中的单列渲染下拉列表,但仅在单元格单击和 replaceData() 时加载
- oauth-2.0 - 在 WSO2 身份服务器中使用 JWT 授予添加声明以访问令牌
- android - Android导航组件saveState和restoreState
- python - 从拆分字符串列创建新列