wp_remote_post code conversion

I'm trying to convert this php code to the wordpress wp_remote_post() format. Thoughts, Ideas, This is NOT my forte, lol.

?php
require_once 'HTTP/Request2.php';
$request = new HTTP_Request2();
$request-setUrl('https://xxxx.yyyyy.zzzzz');
$request-setMethod(HTTP_Request2::METHOD_POST);
$request-setConfig(array(
  'follow_redirects' = TRUE
));
$request-setHeader(array(
  'x-api-key' = 'ppppppppppppppp',
  'Content-Type' = 'application/json'
));
$request-setBody('{\n    "object_type": "Leaderboard",\n    "action": "list",\n    "pagination": {\n       "limit": 5,\n       "order": false\n    },\n    "data": {\n        "username": "[email protected]"\n    }\n}');
try {
  $response = $request-send();
  if ($response-getStatus() == 200) {
    echo $response-getBody();
  }
  else {
    echo 'Unexpected HTTP status: ' . $response-getStatus() . ' ' .
    $response-getReasonPhrase();
  }
}
catch(HTTP_Request2_Exception $e) {
  echo 'Error: ' . $e-getMessage();
}

Topic wp-remote-post Wordpress

Category Web


Use this code :

$url = 'https://xxxx.yyyyy.zzzzz';

$body_array = array(
                        'object_type' => 'Leaderboard',
                        'action' => 'list',
                        'pagination'    => array(
                                                'limit' => 5,
                                                'order' => false
                                            ),
                        'data'          => array(
                                                'username'  => '[email protected]'
                                            )
                    );



$response = wp_remote_post( $url, array(
        'method'      => 'POST',
        'timeout'     => 45,
        'redirection' => 5,
        'httpversion' => '1.0',
        'blocking'    => true,
        'headers'     => array(
                            'x-api-key' => 'ppppppppppppppp',
                            'Content-Type' => 'application/json'
                        ),
        'body'        => json_encode( $body_array ),
        'cookies'     => array()
    )
);

if ( is_wp_error( $response ) ) {
    $error_message = $response->get_error_message();
    echo "Something went wrong: $error_message";
} else {
    echo 'Response:<pre>';
    print_r( $response );
    echo '</pre>';
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.