使用wp_remote_post调用SMS API时出现415错误,请求排查问题
问题:使用wp_remote_post调用SMS API返回415状态码
我在send-sms.php文件中尝试通过wp_remote_post为站点配置SMS API,运行代码后返回状态码为415的响应,无法成功发送短信。以下是我的代码及响应结果:
代码示例
<?php require_once 'wp-load.php'; $url = 'https://api.sprintsmsservice.com/api/SendSMS'; $response = wp_remote_post( $url, array( 'method' => 'POST', 'timeout' => 45, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => array( 'api_id'=>'xxxxxx', 'api_password'=>'xxxxxx', 'sms_type'=>'T', 'encoding'=>'T', 'sender_id'=>'ChonryOTP', 'phonenumber'=>255714812XXX, 'templateid'=>null, 'textmessage'=>'Hello, This is a test message', ), '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>'; } ?>
响应结果
[status_code] => 415 [protocol_version] => 1.1 [success] => [redirects] => 0 [url] => https://api.sprintsmsservice.com/api/SendSMS/ [history] => Array ( ) [cookies] => WpOrg\Requests\Cookie\Jar Object ( [cookies:protected] => Array ( ) ) )
问题分析与解决
HTTP 415错误表示不支持的媒体类型,核心问题是你的请求数据格式或请求头不符合API要求,具体问题点和修复方案如下:
- 缺少必要的请求头声明:当前代码
headers为空,大多数现代SMS API要求接收JSON格式数据,必须添加Content-Type: application/json声明请求体类型。 - 请求体格式不匹配:你传入的是PHP数组,
wp_remote_post默认会将其转为application/x-www-form-urlencoded格式的表单数据,但该API大概率只接受JSON格式,需要把数组转为JSON字符串。 - HTTP版本设置过低:代码中使用
httpversion => '1.0',建议升级为1.1,避免协议兼容性问题。
修改后的代码示例
<?php require_once 'wp-load.php'; $url = 'https://api.sprintsmsservice.com/api/SendSMS'; // 准备请求数据 $body_data = array( 'api_id' => 'xxxxxx', 'api_password' => 'xxxxxx', 'sms_type' => 'T', 'encoding' => 'T', 'sender_id' => 'ChonryOTP', 'phonenumber' => 255714812XXX, 'templateid' => null, 'textmessage' => 'Hello, This is a test message', ); $response = wp_remote_post( $url, array( 'method' => 'POST', 'timeout' => 45, 'redirection' => 5, 'httpversion' => '1.1', // 升级HTTP版本 'blocking' => true, 'headers' => array( 'Content-Type' => 'application/json', // 声明请求体为JSON格式 'Accept' => 'application/json' // 告知API我们接受JSON格式响应 ), 'body' => wp_json_encode($body_data), // 将数组转为JSON字符串 '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>'; } ?>
额外注意事项
- 若API实际接受表单数据,只需将请求头改为
Content-Type: application/x-www-form-urlencoded即可,但415错误更倾向于需要JSON格式; - 确认
templateid字段的要求:部分API不接受null值,可能需要改为空字符串'',具体以API文档为准。
内容的提问来源于stack exchange,提问作者Wilson
相关产品推荐
相关产品推荐

