【问题标题】:convert curl post to wp_remote_post将 curl 帖子转换为 wp_remote_post
【发布时间】:2021-10-05 03:51:34
【问题描述】:

这是运行良好的 curl 代码

$data = array(
        "to" => $to ,
        "from" =>  $options['from_email'] ,
        "subject" => $subject,
        "body" => $message,
 );
$url = 'https://example.com';
$api_key = 'apikeyhere'
              $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Accept: application/json',
        'Content-Type: application/json',
        'X-API-KEY:'.$api_key
    ));         

   $response = curl_exec($ch);

但是,如果我尝试将上面的代码转换为 wp_remote_post,我会遇到错误。

 $response = wp_remote_post( $url, array(
            'method'   => 'POST',
            'timeout'  => 45,
            'blocking' => true, 
            'sslverify' => false,
            'httpversion' => '1.0',
            'redirection' => 5,
            'headers' => array(
                'Accept: application/json',
                'Content-Type: application/json',
                'X-API-KEY:'.$api_key
            ),
            'body'    => json_encode($data),
        ) );

这是我得到的回应

https://pastebin.com/Ap5LpfZb

请告诉我哪里做错了?

【问题讨论】:

  • 您能否分享有关该错误的更多详细信息以及您解决该错误的尝试?
  • 如果我使用 wp_remote_post 并且如果使用 curl 它可以工作 :)
  • [response] => 数组([code] => 500 [message] => 内部服务器错误)
  • 这有帮助吗?尝试将 apikey 添加到 body 属性。 wordpress.stackexchange.com/questions/319157/…

标签: php wordpress curl


【解决方案1】:

我知道头数组有问题,我错误地传递了该数组

错误的代码是

$response = wp_remote_post( $url, array(
            'method'   => 'POST',
            'timeout'  => 45,
            'blocking' => true, 
            'sslverify' => false,
            'httpversion' => '1.0',
            'redirection' => 5,
            'headers' => array(
                'Accept: application/json',
                'Content-Type: application/json',
                'X-API-KEY:'.$api_key
            ),
            'body'    => json_encode($data),
        ) );

这是正确的代码版本

$response = wp_remote_post( $url, array(
            'method'   => 'POST',
            'timeout'  => 45,
            'blocking' => true, 
            'sslverify' => false,
            'httpversion' => '1.0',
            'redirection' => 5,
            'headers' => array(
                'Accept'=> 'application/json',
                'Content-Type' =>'application/json',
                'X-API-KEY' => $api_key,
            ),
            'body'    => json_encode($data),
        ) );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    • 2015-03-11
    相关资源
    最近更新 更多