gpt4 book ai didi

php - 读取 PHP curl_exec 中的错误正文

转载 作者:可可西里 更新时间:2023-11-01 13:30:50 24 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Using PHP curl how does one get the response body for a 400 response

当使用 PHP 的 curl_exec 调用 RESTful API 时,文档显示 http://php.net/manual/en/function.curl-exec.php

Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

当 curl_exec 失败时,它返回 false。但是,远程服务器可能已尝试返回一条有用的消息来解决该错误。当它只返回 false 时,我们如何使用 curl_exec 访问此消息?

例如,远程 API 可能会返回此消息和 HTTP 400 状态代码:

{"Items":[{"Field":"FirstName","Description":"FirstName is required and cannot be null."}]}

目前我无法读取已返回的错误消息,而是我得到的都是错误的。我也看过 curl_info。我确实设置了 returntransfer。

在 C# 中,我会使用 exception.Response.GetResponseStream 方法并编写:

    private static string Post(WebClient client, string uri, string postData)
{
string response = string.Empty;
try
{
response = client.UploadString(uri, "POST", postData);
}
catch (WebException ex)
{
var stream = ex.Response.GetResponseStream(); // here
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
response = reader.ReadToEnd();
}
}
}
return response;
}

这在 PHP 中如何实现? curl_exec 是正确的方法还是我应该使用其他方法?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com