1

This works in php:

$postdata = http_build_query(
        array(
            'api' => get_option('API_key'),
            'gw' => '1'
        )
    );

    $opts = array('http' =>
        array(
            'method'  => 'POST',
            'header'  => 'Content-type: application/x-www-form-urlencoded',
            'content' => $postdata
        )
    );

    $context  = stream_context_create($opts);

    $api_response = file_get_contents('https://myurl.com/api', false, $context);

However, this does not work in Wordpress:

$args = array(
        'method' => 'POST',
        'headers'  => 'Content-type: application/x-www-form-urlencoded',
        'sslverify' => false,
        'api' => get_option('API_key'),
        'gw' => '1'
    );

    $api_response = wp_remote_post('https://myurl.com/api', $args);

It basicly should do the same, but wordpress somehow fails to send the POST data. I want to send the data to server and get the HTML response as $api_response.

  • Looking at the options that wp_remote_post() accepts, I don't see api or gw. What does var_dump( $api_response ); give you in your WordPress code? – Pat J Nov 14 '18 at 3:45
1

You’re passing request params incorrectly.

Take a look at Codex page. You can find such example in there:

$response = wp_remote_post( $url, array(
  'method' => 'POST',
  'timeout' => 45,
  'redirection' => 5,
  'httpversion' => '1.0',
  'blocking' => true,
  'headers' => array(),
  'body' => array( 'username' => 'bob', 'password' => '1234xyz' ),
  'cookies' => array()
   )
);

So in your case it should look something like this:

$args = array(
    'method' => 'POST',
    'headers'  => array(
        'Content-type: application/x-www-form-urlencoded'
    ),
    'sslverify' => false,
    'body' => array(
        'api' => get_option('API_key'),
        'gw' => '1'
    )
);

$api_response = wp_remote_post('https://myurl.com/api', $args);
  • Thank you very much that works. I misunderstood WP documentation, did not know posting data works via Body attribute. Thanks a lot! – LubWn Nov 14 '18 at 10:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.