类文档

Response

💡 云策文档标注

概述

Response 类是 WordPress 中用于处理 HTTP 响应的核心类,继承自 WpOrgRequestsRequests::request() 的返回结果。它封装了响应数据、状态码、头部信息等,并提供方法用于检查重定向、解码 JSON 和抛出异常。

关键要点

  • Response 类包含响应体、原始数据、头部、状态码、协议版本、成功标志、重定向次数、URL、历史记录和 Cookie 等属性。
  • 主要方法包括构造函数 __construct()、检查重定向的 is_redirect()、抛出异常的 throw_for_status() 和 JSON 解码的 decode_body()。
  • decode_body() 方法参数与 PHP 原生 json_decode() 类似,但默认 $associative 为 true,并会抛出异常处理 JSON 错误。

代码示例

// 示例:使用 Response 类处理 HTTP 响应
$response = new WpOrgRequestsResponse();
$response->body = '{"key": "value"}';
$response->status_code = 200;

// 检查是否为重定向
if ($response->is_redirect()) {
    echo 'Response is a redirect.';
}

// JSON 解码响应体
try {
    $data = $response->decode_body();
    print_r($data);
} catch (WpOrgRequestsException $e) {
    echo 'JSON decode error: ' . $e->getMessage();
}

// 抛出状态异常
$response->throw_for_status();

注意事项

  • Response 类通常由 WpOrgRequestsRequests::request() 自动实例化,开发者无需直接调用构造函数。
  • 使用 decode_body() 时需注意默认参数与 PHP json_decode() 的差异,并妥善处理可能抛出的异常。
  • 属性如 $status_code 和 $protocol_version 在非阻塞请求中可能为 false,使用时需进行类型检查。

📄 原文内容

HTTP response class

Description

Contains a response from WpOrgRequestsRequests::request()

Methods

Name Description
Response::__construct Constructor
Response::decode_body JSON decode the response body.
Response::is_redirect Is the response a redirect?
Response::throw_for_status Throws an exception if the request was not successful

Source

class Response {

	/**
	 * Response body
	 *
	 * @var string
	 */
	public $body = '';

	/**
	 * Raw HTTP data from the transport
	 *
	 * @var string
	 */
	public $raw = '';

	/**
	 * Headers, as an associative array
	 *
	 * @var WpOrgRequestsResponseHeaders Array-like object representing headers
	 */
	public $headers = [];

	/**
	 * Status code, false if non-blocking
	 *
	 * @var integer|boolean
	 */
	public $status_code = false;

	/**
	 * Protocol version, false if non-blocking
	 *
	 * @var float|boolean
	 */
	public $protocol_version = false;

	/**
	 * Whether the request succeeded or not
	 *
	 * @var boolean
	 */
	public $success = false;

	/**
	 * Number of redirects the request used
	 *
	 * @var integer
	 */
	public $redirects = 0;

	/**
	 * URL requested
	 *
	 * @var string
	 */
	public $url = '';

	/**
	 * Previous requests (from redirects)
	 *
	 * @var array Array of WpOrgRequestsResponse objects
	 */
	public $history = [];

	/**
	 * Cookies from the request
	 *
	 * @var WpOrgRequestsCookieJar Array-like object representing a cookie jar
	 */
	public $cookies = [];

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->headers = new Headers();
		$this->cookies = new Jar();
	}

	/**
	 * Is the response a redirect?
	 *
	 * @return boolean True if redirect (3xx status), false if not.
	 */
	public function is_redirect() {
		$code = $this->status_code;
		return in_array($code, [300, 301, 302, 303, 307], true) || $code > 307 && $code < 400;
	}

	/**
	 * Throws an exception if the request was not successful
	 *
	 * @param boolean $allow_redirects Set to false to throw on a 3xx as well
	 *
	 * @throws WpOrgRequestsException If `$allow_redirects` is false, and code is 3xx (`response.no_redirects`)
	 * @throws WpOrgRequestsExceptionHttp On non-successful status code. Exception class corresponds to "Status" + code (e.g. WpOrgRequestsExceptionHttpStatus404)
	 */
	public function throw_for_status($allow_redirects = true) {
		if ($this->is_redirect()) {
			if ($allow_redirects !== true) {
				throw new Exception('Redirection not allowed', 'response.no_redirects', $this);
			}
		} elseif (!$this->success) {
			$exception = Http::get_class($this->status_code);
			throw new $exception(null, $this);
		}
	}

	/**
	 * JSON decode the response body.
	 *
	 * The method parameters are the same as those for the PHP native `json_decode()` function.
	 *
	 * @link https://php.net/json-decode
	 *
	 * @param bool|null $associative Optional. When `true`, JSON objects will be returned as associative arrays;
	 *                               When `false`, JSON objects will be returned as objects.
	 *                               When `null`, JSON objects will be returned as associative arrays
	 *                               or objects depending on whether `JSON_OBJECT_AS_ARRAY` is set in the flags.
	 *                               Defaults to `true` (in contrast to the PHP native default of `null`).
	 * @param int       $depth       Optional. Maximum nesting depth of the structure being decoded.
	 *                               Defaults to `512`.
	 * @param int       $options     Optional. Bitmask of JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE,
	 *                               JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR.
	 *                               Defaults to `0` (no options set).
	 *
	 * @return array
	 *
	 * @throws WpOrgRequestsException If `$this->body` is not valid json.
	 */
	public function decode_body($associative = true, $depth = 512, $options = 0) {
		$data = json_decode($this->body, $associative, $depth, $options);

		if (json_last_error() !== JSON_ERROR_NONE) {
			$last_error = json_last_error_msg();
			throw new Exception('Unable to parse JSON data: ' . $last_error, 'response.invalid', $this);
		}

		return $data;
	}
}