WordPress函数:wp_remote_post 发起HTTP post 请求

追格官方小助手/ 2022年07月22日/ WordPress/ 浏览 1392

之前,我们介绍了如何使用 wp_remote_get 发起 HTTP GET 请求,今天继续学习使用 wp_remote_post 发起 HTTP POST 请求。


函数 wo_remote_post 返回的结果(wp_remote_get的结果也一样)如下:


'headers' (string[]) 响应头信息。


'body' (string) 响应体。


'response' (array) HTTP 相关的相应数据。


'code' (int|false) HTTP CODE。


'message' (string|false) HTTP 相应消息。


'cookies' (WP_HTTP_Cookie[]) cookies 信息。


'http_response' (WP_HTTP_Requests_Response|null) 原始的 HTTP 相应。


函数源码:


function wp_remote_post( $url, $args = array() ) {
    $http = _wp_http_get_object();
    return $http->post( $url, $args );
}


使用举例:


$response = wp_remote_post( $url, array(
    'method'      => 'POST',
    '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>';
}

发表评论

暂无评论,抢个沙发...

客服 工单