wp_remote_post 发送 HTTP POST 请求并返回相应

鲍成龙 1.4K 0

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

参数 数据类型 是否必需 描述 默认值
$url 字符串 请求 URL
$args 数字 请求参数 array()

返回值

响应数组,如果出错,返回 WP_Error 对象

使用示例

发送的 Post 数据应该在 body 中提供,body 不一定是数组,也可以是 XML 或 JSON 格式的字符串或其他可以通过 HTTP 协议发送的数据。

$response = wp_remote_post( $url, array(
    'timeout'     => 45,
    'redirection' => 5,
    'httpversion' => '1.0',
    'blocking'    => true,
    'headers'     => array(),
    'body'        => array(
        'username' => 'bob',
        'password' => '1234xyz'
    ),
    'cookies'     => array()
    )
);
 
if ( is_wp_error( $response ) ) {
    $error_message = $response->get_error_message();
    echo "Something went wrong: $error_message";
} else {
    echo 'Response:<pre>';
    print_r( $response );
    echo '</pre>';
}

 

在请求中添加基础授权数据

如果需要添加基础授权数据,参考下面的代码在 header 中添加即可。

$response = wp_remote_post( $url, array(
    'body'    => $data,
    'headers' => array(
        'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password ),
    ),
) );

发表评论 取消回复
表情 图片 链接 代码

分享