【发布时间】:2017-07-02 17:54:05
【问题描述】:
我能够通过 CURL 成功发送 POST 值,但我似乎无法弄清楚如何获取它返回的唯一 JSON 代码。
这是我的代码的一部分:
try {
$curl = curl_init($url);
if (FALSE === $curl)
throw new Exception('failed to initialize');
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json")
);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
$message = curl_exec($curl);
if (FALSE === $message)
throw new Exception(curl_error($curl), curl_errno($curl));
$response = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$error = $message;
var_dump($error);
curl_close($curl);
} catch(Exception $e) {
trigger_error(
sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()
),
E_USER_ERROR
);
}
我能够得到 $response 变量的正确值,但返回的消息给了我:
string(253) "HTTP/1.1 400 Bad Request Cache-Control: no-cache Pragma: no-cache Content-Type: application/json; charset=utf-8 Expires: -1 Server: Microsoft-IIS/8.5 Date: Sun, 02 Jul 2017 17:47:34 GMT Content-Length: 38 {"Message":"Email is already in used"}"
当我尝试使用 var_dump 时。我的目标是为我存储错误消息变量,它是 {"Message":"Email is already in used"}
中的 Message 值有什么建议吗?
非常感谢!
【问题讨论】:
-
你有没有试过在 cURL 执行后进行 json 编码?
-
"400 Bad Request" 向我建议,由于客户端错误,服务器未处理您的请求。端点是否肯定接受 POST 请求? $data 变量是否包含所有必填字段?