要在WordPress中向远程API发出GET和POST请求,你可以使用WordPress的函数wp_remote_get()和wp_remote_post()。以下是如何使用这些函数的示例:
发出GET请求:
$response = wp_remote_get('https://example.com/api/endpoint');if (is_wp_error($response)) { // 处理错误} else { $body = wp_remote_retrieve_body($response); // 获取响应的正文 // 处理响应数据 }
发出POST请求:
$request_args = array( 'body' => json_encode(array('key' => 'value')), // 请求正文,可以是数组等 'headers' => array('ContentType' => 'application/json'), // 设置请求头);$response = wp_remote_post('https://example.com/api/endpoint', $request_args);if (is_wp_error($response)) { // 处理错误} else { $body = wp_remote_retrieve_body($response); // 获取响应的正文 // 处理响应数据 }
上述示例中,你需要将URL替换为你要访问的远程API的实际地址,并根据需要配置请求头和请求正文。
请确保在使用这些函数时处理错误和响应数据,以便有效地与远程API进行通信并处理返回的数据。
原文地址:https://www.2zzt.com/jcandcj/14078.html
还没有评论,来说两句吧...