WordPress cURL and wp_remote_post


WordPress cURL and wp_remote_post

所以我的问题是我直到现在还在我的一个 wordpress 插件中使用cURL用于POST请求,但现在我需要使用 wp_remote_post() .

wp_remote_post看起来很简单,但我无法让它工作。所以我的问题是:有人可以告诉我以下cURL如何转移到wp_remote_post

该网址:

$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields ));
$result = curl_exec($ch);
curl_close($ch);

我的wp_remote_post版本

$result = wp_remote_post($url, array(
    'method' => 'POST',
    'headers' => $headers,
    'body' => json_encode($fields) )
);

我收到 401 错误wp_remote_post因为授权不起作用。

我解决了。出于某种原因,在添加httpversionsslverify之后,它现在可以工作了。

希望这对某人有所帮助:

$result = wp_remote_post($url, array(
    'method' => 'POST',
    'headers' => $headers,
    'httpversion' => '1.0',
    'sslverify' => false,
    'body' => json_encode($fields))
);

之前的答案对我不起作用。也许是因为它从 2015 年开始。

我正在使用我的WordPress插件中的wp_remote_post()。没有curl()电话。

以下内容确实有效,请注意一些添加:超时、重定向和阻塞。可湿性粉剂 5+

$result = wp_remote_post($url, array(
    'method' => 'POST',
    'headers' => $headers,
    'timeout'     => 60, // added
    'redirection' => 5,  // added
    'blocking'    => true, // added
    'httpversion' => '1.0',
    'sslverify' => false,
    'body' => json_encode($fields))
);