curl command to wp_remote_request command

I am trying to translate a curl command into a wp_remote_request command.
Here is the curl command:

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

And here is my PHP

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

The problem is that it just won’t work. I get different errors depending on what i put in the ‘body’, but usually just a ‘404’. The only thing i can think of is that the curl -d is somehow encoding the request, but i can’t figure out how. Any thoughts? Thanks.

By the way, the following works fine, but again i would like to use 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 );

Related posts

Leave a Reply

2 comments

  1. I was fighting wp_remote_request last night. My authentication is in the headers, if you said the curl_setopt_array version worked, than our issues are different, but try including the content length

    $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)
        );
    
  2. You DO NOT want to json_encode the body. Not sure if the method automatically does that or what (seems weird that it would). Remove your json_encode from the body variable and it should work.