我可以成功地使用RESTful发布cURL:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.mindbodyonline.com/public/v6/usertoken/issue');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\n \"Username\": \"Siteowner\",\n \"Password\": \"apitest1234\"\n}");
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Api-Key: {myapikey}';
$headers[] = 'Siteid: 999999';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
print_r($response);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
但是,使用wp_remote_post
的请求似乎是相同的,但未能在头文件中传递"Api-Key“:
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Api-Key: {myapikey}';
$headers[] = 'Siteid: 999999';
$response = wp_remote_post( 'https://api.mindbodyonline.com/public/v6/usertoken/issue', array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => $headers,
'body' => array( 'Username' => 'Siteowner', 'Password' => 'apitest1234' ),
'cookies' => array()
)
);
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
return "Something went wrong: " . $error_message;
} else {
echo 'Response: ';
print_r( $response );
echo '';
return;
}
有没有人在我的语法中发现明显的错误,或者对哪里进行故障排除有建议?我看到wp_remote_post
封装了WP_Http
类。
确认要发送给$headers
的Requests::request
参数如下所示:
Array
(
[0] => Content-Type: application/json
[1] => Api-Key: {myapikey}
[2] => Siteid: 99999
)
检查Requests::request
方法后,$transport
(在此环境中)似乎是以下对象:
Requests_Transport_cURL Object
(
[headers] =>
[response_data] =>
[info] =>
[version] => 468480
[handle:protected] => Resource id #4
[hooks:protected] =>
[done_headers:protected] =>
[stream_handle:protected] =>
[response_bytes:protected] =>
[response_byte_limit:protected] =>
)
在它的request
方法中,报头数组仍然如上。
这很有趣。在Requests_Transport_cURL
s setup_handle
方法中,当设置CURLOPT_HTTPHEADER
时,$headers
如下所示:
Array
(
[0] => 0: Content-Type: application/json
[1] => 1: Api-Key: a3f5be6229744000b9bc25f603e80c45
[2] => 2: Siteid: -99
[3] => Connection: close
)
第385行:
385 curl_setopt($this->handle, CURLOPT_HTTPHEADER, $headers);
因此,也许我需要发送键值对的散列,而不是json字符串的数组。
发布于 2020-03-25 05:53:14
正如上面所发现的,headers
需要(现在看起来很明显)键值对,而不是json风格的键值数组:
$headers = array();
$headers['Content-Type'] = 'application/json';
$headers['Api-Key'] = '{myapikey}';
$headers['Siteid'] = '99999';
body
需要是json
,所以要么是:
'body' => "{\n \"Username\": \"Siteowner\",\n \"Password\": \"apitest1234\"\n}"
或
'body' => json_encode(array( 'Username' => 'Siteowner', 'Password' => 'apitest1234' ))
好时光,好时光。
https://wordpress.stackexchange.com/questions/361382
复制相似问题