Wednesday, November 30, 2022
HomeWordPress Developmentphp - Why is that this particular API request failing when sending...

php – Why is that this particular API request failing when sending by way of wp_remote_post?


I am pulling my hair out making an attempt to make a POST request to an API endpoint utilizing wp_remote_post.

The API wants a request with content-type multipart/blended however WordPress does not appear to play properly with that request sort. It appears to be doing one thing to the POST physique which causes the server to reject it. The response I obtain is 400 Unhealthy Request (nothing particular).

The request works effective when made by way of cURL or Postman. Furthermore, different API requests made by way of WordPress to the identical API (e.g. POST requests with sort utility/json) work effective so I do know it isn’t an issue with connectivity/authorization, or user-agent points on the API aspect.

I believe WordPress is making adjustments to the headers or the physique by some means earlier than sending the request, or simply is not sending the physique as “uncooked” information.

Here is the code:

$physique = "--boundary
Content material-Kind: utility/http

GET /foo/bar
--boundary
Content material-Kind: utility/http

GET /bar/baz
--boundary--";

$endpoint = "https://instance.com/api";

$choices = [
    'body'        => $body,
    'headers'     => [
        'Content-Type' => 'multipart/mixed; boundary=--boundary',
        'Authorization' => 'Bearer sometoken',
    ],
    'data_format' => 'physique'
];

wp_remote_post( $endpoint, $choices );

Right here is an instance of the identical cURL request from Postman which works when submitted by way of Postman or by way of cURL’s command line:

curl -X POST https://instance.com/api 
    -H 'Authorization: Bearer sometoken' 
    -H 'Content material-Kind: multipart/blended;  boundary=boundary' 
    -d '--boundary
Content material-Kind: utility/http

GET /foo/bar
--boundary
Content material-Kind: utility/http

GET /bar/baz
--boundary--
'

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments