Я работаю над PHP-клиентом для своего API и использую Curl для выполнения запроса. Все идет хорошо, но когда есть HTTP-код ответа 400 или выше, я не могу получить заголовки из ответа.
Чтобы получить заголовки от всех ответов, необходим, потому что мой API добавляет дополнительный ответ к ответу с дополнительной информацией о том, что пошло не так.
Если есть способ всегда получить заголовки из ответа в Curl?
$ch = curl_init();
// Convert headers to curlopts
$headers_new = array();
foreach($headers as $key => $value){
if(isset($this->_header_to_curlopt[$key])){
switch($key) {
case self::HEADER_AUTHORIZATION:
if(strstr($value, 'Basic')) {
$value = base64_decode(trim(str_replace('Basic ', '', $value)));
}
break;
case self::HEADER_COOKIE:
if(is_array($value)) {
$value = $this->cookieStringToArray($value);
}
break;
}
curl_setopt($ch, $this->_header_to_curlopt[$key], $value);
unset($this->_requestHeaders[$key]);
}else{
$headers_new[] = $key . ': ' . $value;
}
}
$headers = $headers_new;
// Add length header if it is not set
if(!isset($headers[self::HEADER_CONTENT_LENGTH])){
if(is_array($data)) {
$headers[self::HEADER_CONTENT_LENGTH] = strlen(http_build_query($data, '', '&'));
} else {
$headers[self::HEADER_CONTENT_LENGTH] = strlen($data);
}
}
// Set headers
if(count($headers)){
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Don't output content
curl_setopt($ch ,CURLOPT_TIMEOUT, $timeout); // Timeout
switch($method){
case self::METHOD_POST:
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
break;
case self::METHOD_GET:
if(count($this->_data)) {
$separator = strstr($url, '?') ? '&' : '?';
$url .= $separator . http_build_query($this->_data, '', '&');
}
break;
default:
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
break;
}
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
// Use SSL
if(strtolower(substr($url, 0, 5)) == 'https') {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Separate content and headers
$result = str_replace("\r\n\r\nHTTP/", "\r\nHTTP/", $result);
$parts = explode("\r\n\r\n",$result);
$headers = array_shift($parts);
$result = implode("\r\n\r\n", $parts);