0

Following examples found here and in API, I tried 2 methods, both return a bad request status message.

First method

$data = 'name=value&name1=value1';

$options = array(
  'method' => 'GET',
  'data' => $data,
  'timeout' => 15,
  'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
);

$result = drupal_http_request('http://example.com/foo', $options);

dpm($result);

Second method

$data = array(
  'key1' => $value1,
  'key2' => $value2,
);

$full_url = url('http://example.com/foo', array('query' => $data));

$options = array(
  'method' => 'GET',
  'timeout' => 15,
  'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
);
$result = drupal_http_request($full_url, $options);

dpm($result);

Which one is the good one and what's wrong ? Thank you

Edit

This is dpm($result)

enter image description here

2

The first method is correct; you don't use url() to pass the data. Also, application/x-www-form-urlencoded is the content type used when POSTing data.

You could also use drupal_http_build_query() to build the data to pass.

$data = array('name' => 'value', 'name1' => 'value1');

$options = array(
  'method' => 'GET',
  'data' => drupal_http_build_query($data),
  'timeout' => 15,
);

$result = drupal_http_request('http://example.com/foo', $options);
| improve this answer | |
  • Thanks a lot. I added dpm($result) in the question. So if this is correct, does the bad request means that the code is ok, but the target website was expecting another query ? – Kojo Dec 6 '15 at 14:02
  • Bad request means the server cannot understand the request, which could simply be because you are setting the content type that is expected from a POST, or because you are passing the wrong data for example.com/foo. I would think it is the first case. – kiamlaluno Dec 6 '15 at 15:13
  • All rights, I'll check better the remote expected configuration. Grazie mile per il suo tempo ;) – Kojo Dec 6 '15 at 17:04
  • The second method is correct if you're wanting to pass the data as query parameters: $full_url = url('http://example.com/foo', array('query' => $data)); The 'data' option only refers to the body of the request, not the query parameters. See: api.drupal.org/api/drupal/includes%21common.inc/function/… – imclean Dec 12 '18 at 21:55

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.