WordPress使用WP_Http_Curl请求报错certificate

WordPress有wp_remote_post()和wp_remote_get()数据请求函数,这两个函数其实也是使用WP_Http类来请求的。另外还有一个WP_Http_Curl类,这个类可以通过hook来自定义Curl选项。

使用WP_Http_Curl类容易得到一个错误:

wordpress error setting certificate verify locations: CAfile: CApath: none

解决的方法是在参数中指定证书路径:

'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt'

使用WP_Http_Curl类还必须传递一些参数,一个POST上传文件的请求如下:

$http = new WP_Http_Curl;
$response = $http->request($url, [
	'method' => 'POST',
	'sslverify' => true,
	'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt',
	'user-agent' => 'WordPress/' . $wp_version . '; ' . home_url('/'),
	'stream' => false,
	'decompress' => false,
	'timeout' => 600,
	'filename' => basename($file),
	'body' => [
		'file' => new \CurlFile($file)
	]
]);

判断请求是否成功,如果失败则返回错误信息:

if (is_wp_error($response)) {
	return $response->get_error_message();
}

获取返回的header信息:

wp_remote_retrieve_header($response);

获取返回的数据:

wp_remote_retrieve_body($response);
阿里云