I am developing a module for Drupal 7 which calls a remote API. I am using drupal_http_build_query(), drupal_http_request(), and drupal_json_decode().
My code is as follows
$username = $form_state['input']['name'];
$password = $form_state['input']['pass'];
$authurl = variable_get('sgauth_base_url_authenticate', '');
$headers = array('Content-Type' => 'application/json');
$data = array('email' => $username, 'password' => $password);
$query = drupal_http_build_query($data);
$options = array('headers' => $headers, 'method' => 'POST', 'data' => $query);
$result = drupal_http_request($authurl, $options);
dpm($result);
$authurl is returning the correct url for the API.
When I look at the returned object I see the following
The request is (Note host, username and password have been hidden)
POST /SingPostApi/MobileAuthenticate HTTP/1.0
Content-Type: application/json
User-Agent: Drupal (+http://drupal.org/)
Host: xxxxxxxxxxxx.xxxxxxxxxx.com
Content-Length: 36
email=xxx%40xx.xxx&password=xxxxxxxx
Which seems OK
$result->code I see a 500 error
$result->data shows Invalid JSON primitive: email.
As far as I can tell my code is OK based on my reading of the Drupal API. I don't understand why I am getting the wrong data returned.
When I make he POST request from the Firefox HTTP Requester I get a 200 code and the data I expect to see returned
I would appreciate it if someone who can see where I am going wrong can point me in the right direction.
email=xxx%40xx.xxx&password=xxxxxxxx
is nothing like JSON, that's a URL encoded string. Since you're telling the server at the other end that you're sending JSON, and you're not, it's fair enough that it's getting confused and bailing out. Tell the other server you're sending a url encoded string, assuming it supports that, and your code will work, or change the code to$query = json_encode($data);
.drupal_http_request()
is just proxying the data you're giving it straight to the network, it never changes anything, so if it's not working always check your own logic$form_state['input']
. Use$form_state['values']
. 'input' is unsafe, unvalidated data.