将CURL请求转换为Wordpress wp_remote_post

时间:2014-03-31 13:58:07

标签: php wordpress curl wordpress-plugin

我需要将一个PHP库从CURL转换为wp_remote_post以用于Wordpress插件。

我参考了Wordpress wp_remote_post page here

这是我尝试转换的代码..

 $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $scheme . $url['host'] . $url['path']);
        curl_setopt($ch, CURLOPT_PORT, $port);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_USERAGENT, $this->_config['UserAgent']);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
        curl_setopt($ch, CURLOPT_HEADER, true); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = "";
        $response = curl_exec($ch);

        if ($response === false) {
            $errorResponse = curl_error($ch);
            require_once("FBAOutboundServiceMWS/Exception.php");
            curl_close($ch);

            throw new FBAOutboundServiceMWS_Exception(array(
                'Message' => $errorResponse,
                'ErrorType' => 'HTTP'
            ));
        }

        curl_close($ch);

这就是我所想的'是正确的,但不起作用......

$THEurl = $scheme . $url['host'] . $url['path'];
    $response = wp_remote_post( $THEurl, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'httpversion' => '1.0',
        'blocking' => true,
        'headers' => array(),
        'body' => $query,
        'cookies' => array()
        )
    );

    if ( is_wp_error( $response ) ) {
       $errorResponse = $response->get_error_message();
            require_once("FBAOutboundServiceMWS/Exception.php");
            curl_close($ch);

            throw new FBAOutboundServiceMWS_Exception(array(
                'Message' => $errorResponse,
                'ErrorType' => 'HTTP'
            ));
    } 

wp_remote_post实际执行的时间点是什么时候?就在调用函数时? 非常感谢您的帮助;)

1 个答案:

答案 0 :(得分:2)

为我试一试,看看你得到了什么

$THEurl = $scheme . $url['host'] . $url['path'];
$response = wp_remote_post( $THEurl, array(
    'method' => 'POST',
    'timeout' => 45,
    'redirection' => 5,
    'httpversion' => '1.0',
    'blocking' => true,
    'headers' => array(),
    'body' => $query,
    'cookies' => array()
    )
);

if ( is_wp_error( $response ) ) {
    $errorResponse = $response->get_error_message();
    require_once("FBAOutboundServiceMWS/Exception.php");

    throw new FBAOutboundServiceMWS_Exception(
        array(
            'Message' => $errorResponse,
            'ErrorType' => 'HTTP'
        )
    );
} else {
    echo 'Response:<pre>';
    print_r( $response );
    echo '</pre>';
}

取出您不需要的代码,并添加到您之前没有做过的回复中。