d3no
d3no

Reputation: 121

Guzzle 400 Bad Request

I get the following error when I'm doing a POST request:

Client error: POST http://api.hitbox.tv/auth/login resulted in a 400 Bad Request response: {"success":true,"error":false,"error_msg":"auth_failed"}

I'm not sure, is that because I have anything wrong with my guzzle code

require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;

$client = new Client(["base_uri"=>"http://api.hitbox.tv/"]);
$data = ["login"=>"myId","pass"=>"mypassword","rememberme"=>"",];
try{
$response = $client->request("POST","auth/login",["form-params"=>$data,"content-type"=>"application/x-www-form-urlencoded"]);   
}
catch(ClientException $e){

  echo  $e->getMessage();

}
catch(InvalidArgumentException $e){

    echo $e->getMessage();

}
var_dump(json_decode($response,true));

I have tried the same api with Javascript XMLHttpRequest to POST the same set of data,where I got a success result.

var xmlhttp;


var data = '{"login":"myId","pass":"myPassword","rememberme":""}';

if(window.XMLHttpRequest){
    xmlhttp = new XMLHttpRequest();      
}
else{              
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){

if(xmlhttp.readyState==4 && xmlhttp.status == 200){
    return xmlhttp.responseText;
}

xmlhttp.open('POST','https://api.hitbox.tv/auth/login',false);

xmlhttp.send(data);

Upvotes: 3

Views: 4217

Answers (1)

Bartosz Zasada
Bartosz Zasada

Reputation: 3900

You are sending two different requests. With JavaScript, you send the data as JSON in the request body. With Guzzle however, you're using form-params, which is a different format.

To fix this, just replace form-params key with json and remove "content-type"=>"application/x-www-form-urlencoded".

Upvotes: 3

Related Questions