I am experiencing odd behavior with the wp_remote_retrieve_body() function.

When making a post request, I am able to see the response correctly in POSTMan. The API returns only a string value.

However, for some reason, the wordpress function wp_remote_retrieve_body() does not work. I use wp_remote_post() for the post request. the POST Request works fine, however wp_remote_retrieve_body() does not return the body contents.

I reviewed the codex and found its implementation

function wp_remote_retrieve_body(&$response) { if ( is_wp_error($response) || ! isset($response['body']) ) return ''; return $response['body']; } 

I assumed there must be a mistake with my $response. Below is my code

$id_ref = 'noerror'; if ( is_wp_error($response) || ! isset($response['body']) ){ $link_pos_id_ref = 'someerror'; } 

I hoped that the variable would update itself to 'someerror'. It did. SO I further attempted to drill down to the issue -

$id_ref = 'noerror'; if ( is_wp_error($response)){ $id_ref = 'weberror'; } if(! isset($response['body']) ){ $id_ref = 'isseterror'; } 

This time however, the value did not change. It was still 'noerror' So I checked the value for $response['body'] and found that It did contain the string!

I verified that the response was a 200 OK. So at this point, I can use $response['body'] to get my string value, but I have no further ideas as to how to go about investing this issue.

Maybe its strange that the API is returning a simple string instead of a JSON? I really dont want to keep using $response['body'] as I found like to keep good coding practices.

4

1 Answer

It is likely that you were using the 'blocking' => false parameter in your request args which makes the call asynchronous and thus doesn't return a response.

If you set 'blocking' => true you will get a response.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.