WordPress cURL和wp_remote_post

时间:2015-01-13 09:41:15

标签: php wordpress post curl

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

wp_remote_post似乎很简单,但我无法让它发挥作用。所以我的问题是:有人可以告诉我以下cURL如何转移到wp_remote_post吗?

cURL:

$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) )
);

我在wp_remote_post时收到401错误,因为授权无效。

2 个答案:

答案 0 :(得分:4)

我解决了。由于某些原因,在添加httpversion和sslverify之后它现在正在工作。希望这有助于某人:

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

答案 1 :(得分:0)

先前的答案对我不起作用。 也许是因为它来自2015年。

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

以下内容确实起作用,请注意一些附加内容:超时,重定向和阻止。 WP 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))
);