当前浏览:首页 / WordPress函数 / wp_remote_get()

wp_remote_get( string $url, array $args = array() )

使用GET方法执行HTTP请求并返回其响应

remote 远程


描述

另见

  • wp_remote_request():有关响应数组格式的详细信息。
  • WP_Http::request():获取默认参数信息。

参数

$url

(string)(必填) 要检索的URL。

$args

(array)(可选) 请求参数。

默认值: array()


返回

(array|WP_Error) 响应(response)结果,或失败时的WP_Error


更多信息

使用 wp_remote_retrieve_body( $response ) 获取响应的body。

使用 wp_remote_retrieve_response_code( $response ) 获取响应的HTTP状态码。

使用wp-includes/http.php中的相关函数获取其他参数,如headers。

有关wp_remote_get().返回的数组的格式,请参见位于wp-includes/class-wp-http-streams.phpWP_Http_Streams::request()方法。

更多信息请查阅:插件开发手册 - HTTP API



源码

查看源码 官方文档


更新日志

版本描述
2.7.0开始引入

使用示例

  • 示例1

    第二个参数的有效参数可以在class-http.php中找到。在本指南的当前版本中,没有简单的方法来引用该列表,因此我将PHPDoc header粘贴在这里。希望docs站点能够扩展WP_Http页面,或者在机器人构建这些页面时找到一种通过间接引用有效参数的方法。

    * @param string|array $args {
    * Optional. Array or string of HTTP request arguments.
    *
    * @type string $method Request method. Accepts 'GET', 'POST', 'HEAD', or 'PUT'.
    * Some transports technically allow others, but should not be
    * assumed. Default 'GET'.
    * @type int $timeout How long the connection should stay open in seconds. Default 5.
    * @type int $redirection Number of allowed redirects. Not supported by all transports
    * Default 5.
    * @type string $httpversion Version of the HTTP protocol to use. Accepts '1.0' and '1.1'.
    * Default '1.0'.
    * @type string $user-agent User-agent value sent.
    * Default WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ).
    * @type bool $reject_unsafe_urls Whether to pass URLs through wp_http_validate_url().
    * Default false.
    * @type bool $blocking Whether the calling code requires the result of the request.
    * If set to false, the request will be sent to the remote server,
    * and processing returned to the calling code immediately, the caller
    * will know if the request succeeded or failed, but will not receive
    * any response from the remote server. Default true.
    * @type string|array $headers Array or string of headers to send with the request.
    * Default empty array.
    * @type array $cookies List of cookies to send with the request. Default empty array.
    * @type string|array $body Body to send with the request. Default null.
    * @type bool $compress Whether to compress the $body when sending the request.
    * Default false.
    * @type bool $decompress Whether to decompress a compressed response. If set to false and
    * compressed content is returned in the response anyway, it will
    * need to be separately decompressed. Default true.
    * @type bool $sslverify Whether to verify SSL for the request. Default true.
    * @type string sslcertificates Absolute path to an SSL certificate .crt file.
    * Default ABSPATH . WPINC . '/certificates/ca-bundle.crt'.
    * @type bool $stream Whether to stream to a file. If set to true and no filename was
    * given, it will be droped it in the WP temp dir and its name will
    * be set using the basename of the URL. Default false.
    * @type string $filename Filename of the file to write to when streaming. $stream must be
    * set to true. Default null.
    * @type int $limit_response_size Size in bytes to limit the response to. Default null.

  • 示例2

    获取远程URL

    /** @var array|WP_Error $response */
    $response = wp_remote_get( 'http://www.example.com/index.html' );
    
    if ( is_array( $response ) && ! is_wp_error( $response ) ) {
    	$headers = $response['headers']; // array of http header lines
    	$body    = $response['body']; // use the content
    }
    
  • 示例3

    上面Store Locator Plus的评论添加了良好的信息,但很难阅读。

    要查找参数,您可以查看WP_Http::request documentation,或查看以下格式化的PHPDoc版本:

    /**
    * @param string|array $args {
    *     Optional. Array or string of HTTP request arguments.
    *
    *     @type string       $method              Request method. Accepts 'GET', 'POST', 'HEAD', 'PUT', 'DELETE',
    *                                             'TRACE', 'OPTIONS', or 'PATCH'.
    *                                             Some transports technically allow others, but should not be
    *                                             assumed. Default 'GET'.
    *     @type float        $timeout             How long the connection should stay open in seconds. Default 5.
    *     @type int          $redirection         Number of allowed redirects. Not supported by all transports
    *                                             Default 5.
    *     @type string       $httpversion         Version of the HTTP protocol to use. Accepts '1.0' and '1.1'.
    *                                             Default '1.0'.
    *     @type string       $user-agent          User-agent value sent.
    *                                             Default 'WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ).
    *     @type bool         $reject_unsafe_urls  Whether to pass URLs through wp_http_validate_url().
    *                                             Default false.
    *     @type bool         $blocking            Whether the calling code requires the result of the request.
    *                                             If set to false, the request will be sent to the remote server,
    *                                             and processing returned to the calling code immediately, the caller
    *                                             will know if the request succeeded or failed, but will not receive
    *                                             any response from the remote server. Default true.
    *     @type string|array $headers             Array or string of headers to send with the request.
    *                                             Default empty array.
    *     @type array        $cookies             List of cookies to send with the request. Default empty array.
    *     @type string|array $body                Body to send with the request. Default null.
    *     @type bool         $compress            Whether to compress the $body when sending the request.
    *                                             Default false.
    *     @type bool         $decompress          Whether to decompress a compressed response. If set to false and
    *                                             compressed content is returned in the response anyway, it will
    *                                             need to be separately decompressed. Default true.
    *     @type bool         $sslverify           Whether to verify SSL for the request. Default true.
    *     @type string       $sslcertificates     Absolute path to an SSL certificate .crt file.
    *                                             Default ABSPATH . WPINC . '/certificates/ca-bundle.crt'.
    *     @type bool         $stream              Whether to stream to a file. If set to true and no filename was
    *                                             given, it will be droped it in the WP temp dir and its name will
    *                                             be set using the basename of the URL. Default false.
    *     @type string       $filename            Filename of the file to write to when streaming. $stream must be
    *                                             set to true. Default null.
    *     @type int          $limit_response_size Size in bytes to limit the response to. Default null.
    *
    * }
    */
    
  • 示例4

    获取带有特殊参数的远程URL

    /** @var array|WP_Error $response */
    $response = wp_remote_get( 'http://www.example.com/index.php?action=foo',
    	array(
    		'timeout'     => 120,
    		'httpversion' => '1.1',
    	)
    );
    
  • 示例5

    添加headers时,header的每个部分都必须是一个单独的元素,如下所示:

    $args = array(
    	  'headers' => array(
    		'Content-Type' => 'application/json',
    		'X-Api-Key' => 'apikey12345'
    	  ) 

    不像cURL那样,您可以在其中使用‘Content-Type: application/json’

  • 示例6

    在这个页面的某个地方有一个链接会很酷:wp_safe_remote_get()

  • 示例7

    替换wp_get_http( $url, $filename )以获取远程文件并写入文件系统:

    $args_for_get = array(
    	'stream' => true,
    	'filename' => $filename,
    );
    $response = wp_remote_get( $url, $args_for_get );

    感谢@charlestonsw在评论中粘贴所有args的含义,这使我找到了这个简单的替换。

  • 示例8

    如果您从API加载数据并对API密钥设置了域限制(例如仅允许在“www.example.com/*”),则需要在$args中的“headers”中设置“referer”,因为wp_remote_get()不会自动设置referer:

    $response = wp_remote_get(
    	esc_url_raw( $api_url ),
    	array(
    		'headers' => array(
    			'referer' => home_url()
    		)
    	)
    );

    或者,作为字符串,也可以在本地主机上工作:

    'referer' => 'www.example.com'
  • 示例9

    最好执行这样的JSON响应以保持对其的管理。

    $request = wp_remote_get($url, $options);
    
    return load_request($request);
    
    function load_request($response) {
      try {
        $json = json_decode( $response['body'] );
      } catch ( Exception $ex ) {
        $json = null;
      }
      return $json;
    }
    
  • 示例10

    从API端点读取JSON响应并进行错误检查的示例。
    在这里,我们使用wp_remote_retrieve_response_code()函数检查200的响应代码,并使用json_last_error()功能验证json_decode()。

    try {
    	$response = wp_remote_get( 'https://yourapi.end/point/', array(
    		'headers' => array(
    			'Accept' => 'application/json',
    		)
    	) );
    	if ( ( !is_wp_error($response)) && (200 === wp_remote_retrieve_response_code( $response ) ) ) {
    		$responseBody = json_decode($response['body']);
    		if( json_last_error() === JSON_ERROR_NONE ) {
    			//Do your thing.
    		}
    	}
    } catch( Exception $ex ) {
    	//Handle Exception.
    }
    
  • 示例11
        $apiUrl = 'https://example.com/wp-json/wp/v2/posts?page=0&per_page=0';
        $response = wp_remote_get($apiUrl);
        $responseBody = wp_remote_retrieve_body( $response );
        $result = json_decode( $responseBody );
        if ( is_array( $result ) && ! is_wp_error( $result ) ) {
            // Work with the $result data
        } else {
            // Work with the error
        }