curl命令到wp_remote_request命令

时间:2013-06-18 21:27:04

标签: curl wordpress-plugin

我正在尝试将curl命令转换为wp_remote_request命令 这是curl命令:

curl -v 
-H "Accept:application/json" -H "Content-type:application/json" 
-X POST -d '{"user":{"password":"***","email":"***"}}'
http://***/users/sign_in.json

这是我的PHP

$t = array(
     "user" => array(
               "password" => "***", 
               "email" => "***"));

$args = array (      
    'headers' => 
    array (
        'Accept'       => 'application/json',
        'Content-Type' => 'application/json',
    ),
    'method'    => 'POST',
    'body'      => json_encode( $t )
);

$response = wp_remote_request( 
           'http://***/users/sign_in.json' , $args );

问题在于它无法正常工作。根据我在“身体”中的含义,我会得到不同的错误,但通常只是'404'。我唯一能想到的是curl -d以某种方式编码请求,但我无法弄清楚如何。有什么想法吗?谢谢。

顺便说一下,以下工作正常,但我想再次使用wp_remote_request

$t = array('user' => array('password' => '***',  
                           'email'    => '***'));
$curl = curl_init();

curl_setopt_array( $curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://***/users/sign_in.json',
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => json_encode($t),
    CURLOPT_HTTPHEADER => array('Content-Type: application/json')
));

$resp = curl_exec( $curl );
curl_close( $curl );

1 个答案:

答案 0 :(得分:0)

昨晚我和wp_remote_request打架了。我的身份验证在标题中,如果您说curl_setopt_array版本有效,那么我们的问题就不同了,但请尝试包含内容长度

$headers = array(
        'Authorization'  => 'Basic ' . base64_encode( $this->key.':'.$this->password ),
        'Accept'       => 'application/json',
        'Content-Type'   => 'application/json',
        'Content-Length' => strlen( json_encode($body) )
    );

    // Setup variable for wp_remote_post
    $post = array(
        'method'    => 'POST',
        'headers'   => $headers,
        'body'      => json_encode($body)
    );