首页 小组 问答 话题 好文 素材 用户 唠叨 我的社区

[分享]wp_remote_get发送GET请求到URL并返回数据

九秘Lv.1种子选手
2024-10-02 09:56:09
0
36

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

参数

数据类型

是否必需

描述

默认值

$url

字符串

请求URL

$args

数组

请求参数

array()

函数返回值

成功时,返回一个数组,失败时,返回一个WP_Error对象

使用示例

发送HTTP请求时,我们可以通过该函数的$args参数来设置HTTP的各种参数,包括超时时间,HTTP版本,Headers等信息。

请求时设置超时时间和HTTP版本。

$response = wp_remote_get( 'http://www.example.com/index.php?action=foo',
    array(
        'timeout'     => 120,
        'httpversion' => '1.1',
    )
);

请求时设置内容类型和API Key。

$args = array(
    'headers' => array(
        'Content-Type' => 'application/json',
        'X-Api-Key' => 'apikey12345'
    )
)
 
$response = wp_remote_get( $url, $args );
if ( is_array( $response ) && ! is_wp_error( $response ) && $response['response']['code'] == '200' ) {
    $headers = $response['headers']; 
    $body = $response['body']; 
}
九秘
九秘

20 天前

签名 : 我常驻在>https://www.huaqu.club/ask   36       0
评论
站长交流