
wp_remote_post 发送 HTTP POST 请求并返回相应
函数功能
使用POST方法执行HTTP请求并返回其响应数据。
参数
参数 | 数据类型 | 是否必需 | 描述 | 默认值 |
---|---|---|---|---|
$url | 字符串 | 是 | 请求 URL | 无 |
$args | 数字 | 否 | 请求参数 | array() |
返回值
响应数组,如果出错,返回 WP_Error 对象
使用示例
发送的Post数据应该在 body 中提供,body 不一定是数组,也可以是 XML 或 JSON 格式的字符串或其他可以通过 HTTP 协议发送的数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | $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:<pr e>'; print_r( $response ); echo '</ pr e>'; } |
在请求中添加基础授权数据
如果需要添加基础授权数据,参考下面的代码在 header 中添加即可。
1 2 3 4 5 6 | $response = wp_remote_post( $url, array( 'body' => $data, 'headers' => array( 'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password ), ), ) ); |
相关函数
wp_safe_remote_post