How to send the body in wp_remote_post as “raw”?

Question

I’m not sure if I’m asking the right question, so here is the context.

I’m making a POST to an API (The api is to a Google Sheets Script – so there are some unusual limitations). When I use postman the data is returned in a json file. In order to get it to work in postman I have to send the parameters via the body and I have to select the raw option. Selecting any other option(i.e. x-www-form-urlencoded or form-data) results in an html error page.

I’ve followed the steps for wp_remote_post($api_url , $body ); in the WordPress documentation – but I’m getting the html error instead of the expected data.

How do I send the body as “raw” just like it’s being sent in Postman?

UPDATE – To add code.

$api_url = 'https://script.google.com/macros/s/UNIQUE_KEYw/exec';
// $body = array(
//  "method"=>"GET",
//  "sheet"=>"date",
//  "key"=>"PASSWORD");

$body = ('{n"method": "GET",n"sheet": "date",n"key": "PASSWORD"n}');

$request =  wp_remote_post($api_url , array(
    'method'      => 'POST',
    'headers'     => ["Content-Type" => "raw"],
    'body'        => $body,
    'data_format' => 'body'
    )
                          );

The HTTP_Request2 snippet from postman that I’m trying to recreate.

<?php
require_once 'HTTP/Request2.php';
$request = new HTTP_Request2();
$request->setUrl('https://script.google.com/macros/s/UNIQUE_KEY/exec');
$request->setMethod(HTTP_Request2::METHOD_POST);
$request->setConfig(array(
  'follow_redirects' => TRUE
));
$request->setHeader(array(
  'Content-Type' => 'text/plain'
));
$request->setBody('{n"method": "GET",n"sheet": "date",n"key": "PASSWORD"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();
}
0
Brendan Quigley 4 months 0 Answers 22 views 0

Leave an answer