wp_remote_post sends an HTTP POST request and returns the corresponding

Posted in:
Update time:2024-01-05

function function

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

parameters

parametersdata typeRequired or notdescriptivedefault value
$urlstring (computer science)beRequest URLnot have
$argsarraysclogged请求参数array()

return value

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

usage example

发送的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 ),
    ),
) );

related function

wp_safe_remote_post: wp_remote_post 的带安全验证的版本

wp_remote_get: 用 GET 方法从 URL 中获取数据

We offer WordPress Themes and Plugins Custom Development Services

This site has long undertaken WordPress themes, plugins, WooCommerce-based store mall development business. We have 10 years of experience in WordPress development, if you want to Developing Websites with WordPress, please contact WeChat: iwillhappy1314 or email: amos@wpcio.com for inquiries.

发表回复

Your email address will not be published. 必填项已用 * 标注

*