Home > Software design >  How to make post request to get data Laravel Guzzle?
How to make post request to get data Laravel Guzzle?

Time:06-29

Let say, the Secret Key is XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX and md5key is YYYYYYYY. I made a Query String QS Qs = “method=RegUserInfo&Key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&Time=20140101123456&Username=DemoUser001”;

After urlencode I got q='j4tjorjwarfj3trwise0safrwg2wt4awari0fwjfeoh'

I made MD5 String for building the signature (QS md5key Time Key): s = BuildMD5(QS “YYYYYYYY” “20140101123456” “XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX”); I got s='1234567890abcdef'

So will get q=j4tjorjwarfj3trwise0safrwg2wt4awari0fwjfeoh&s=1234567890abcdef

How to resulting POST method query (using “Content-Type: application/x-www-form-urlencoded”) by POST to http://xxxxx.com/api/api.aspx

My code is

   $param = "q=".$q."&s=".$s;
 
    $client = new Client(['headers' => [
        'Content-Type' => 'application/x-www-form-urlencoded',
        ]]);
    try{
        $response = $client->request('POST','http://xxxxxx.com/api/api.aspx', [
            'query' => [$param],
    ]);
    }catch(ClientException $e){
        $response = $e->getResponse();
        $responseBodyAsString = $response->getBody()->getContents();
        dd($responseBodyAsString);
    }
    
}

but I get 403 Forbidden

CodePudding user response:

If you want Content-Type: application/x-www-form-urlencoded you need to use form_params request option.

try{
  $client = new \GuzzleHttp\Client(['headers' => ['Authorization' => 'Bearer ' . $your_token]]);
  
  $guzzleResponse = $client->post(
                $api_url, [
                'form_params' => [
                    'grant_type' => 'xxxxx',
                    'key' => 'xxx',
                    'time' => 'xxxx', 
                    'username' => 'xxxxxx'
                ]
            ]);
    if ($guzzleResponse->getStatusCode() == 200) {
         $response = json_decode($guzzleResponse->getBody(),true);
         //perform your action with $response 
    } 
}
catch(\GuzzleHttp\Exception\RequestException $e){
   // you can catch here 40X response errors and 500 response errors

}catch(Exception $e){
   //other errors 
}

know more about form_params

  • Related