I am a new for using Guzzle package i want to send data via web api when response coming with status OK or NOT i do some action otherwise status equal waiting i request again after 5second or status equal not yet sleep for 30 second.
this is my code
$client = new Client();
$headers= [
'Accept' => 'application/x-www-form-urlencoded',
'Content-Type' => 'application/x-www-form-urlencoded',
];
$body = [
'phone2'=>'723457481',
'amount'=>'200'
];
$url = "http://192.168.31.51:8080/requesttrafic/";
$response = $client->Request("POST", $url, [
'handler' => $stack,
'headers'=>$headers,
'form_params'=>$body
]);
$contents = (string) $response->getBody();
// this $contents can be status 'ok','not' anything
So how can I send again according response status ?
Thanks
if you want to send it again if status is not 'ok' then:
if($contents!=='ok'){
$response = $client->Request("POST", $url, [
'handler' => $stack,
'headers'=>$headers,
'form_params'=>$body
]);
$contents = (string) $response->getBody();
}
if by status you meant http status then you can verify that like this:
$status = $response->getStatusCode();
if($status!==200){
//your request again
}
or maybe i understood your question wrong. In that case please elaborate.
$response = $client->Request("POST", $url, [
'handler' => $stack,
'headers'=>$headers,
'form_params'=>$body
]);
$contents = (string) $response->getBody();
if($contents!=='ok'){
$response = $client->Request("POST", $url, [
'handler' => $stack,
'headers'=>$headers,
'form_params'=>$body
]);
$contents = (string) $response->getBody();
if($contents!=='ok'){
$response = $client->Request("POST", $url, [
'handler' => $stack,
'headers'=>$headers,
'form_params'=>$body
]);
$contents = (string) $response->getBody();
}else{
exit;
}
}
Related
I'm trying out guzzle in mu laravel app in order to use FCM notifications, for some reason I'm getting the following error when I try to get response status code, also am I using guzzle correct syntax? they seem to have updated theirs.
Call to undefined method GuzzleHttp\\\\Psr7\\\\Stream::getStatusCode()
My method:
public function send($user,$title,$body, $data = false , $type, $image='')
{
$client = new Client();
$url = 'https://fcm.googleapis.com/fcm/send';
$serverKey = config('services.firebase.api_key');
$headers =
[
'Content-Type' => 'application/json',
'Authorization' => 'key='.$serverKey,
];
$fields =
[
'registration_ids' => [ $user['fcm_token'] ],
'to' => $user['fcm_token'],
"notification" =>
[
"title" => $title,
"body" => $body,
"sound" => "default",
],
"priority" => 10,
'data' => $data,
"android" => [ "priority" => "high" ]
];
$fields = json_encode ( $fields );
try
{
$response = $client->request('POST',$url,[
'headers' => $headers,
"body" => $fields,
]);
$response = $response->getBody();
$statusCode = $response->getStatusCode();
}
catch (ClientException $e)
{
$response = $e->getResponse();
$response = $response->getBody()->getContents();
$statusCode = $response->getStatusCode();
}
$result =
[
'response' => $response,
'statusCode' => $statusCode
];
return $result;
}
Thanks in advance
You are overwriting the response and then trying to get the status code from the stream. You should instead do
$response = $e->getResponse();
$statusCode = $response->getStatusCode();
$response = $response->getBody()->getContents();
Notice I moved the getStatus method
above the getBody.
I need to send a request to an api with auth headers
here is what I've tried so far
$client = new \yii\httpclient\Client(['baseUrl' => 'https://link']);
$response = $client->createRequest()
->setMethod('GET')
->addHeaders(['authorization' => 'token'])
->send();
var_dump($response);
//other
$client = new \GuzzleHttp\Client();
$headers = ['authorization' => 'token'];
$body = 'Hello!';
$request = new \GuzzleHttp\Psr7\Request('GET', 'https://link', $headers, $body);
$response = $client->send($request, ['timeout' => 2]);
$curl = new \linslin\yii2\curl\Curl();
$response = $curl->setHeaders($headers)->get('link', $headers);
var_dump($response);
// other
$opts = [
"http" => [
"method" => "GET",
"header" => "authorization:token\r\n",
],
];
$context = stream_context_create($opts);
$file = file_get_contents('link', false, $context);
var_dump($file);
// other
$ch = curl_init();
$headers = ["authorization:token"];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); # custom headers, see above
$result = curl_exec($ch); # run!
// curl_close($ch);
var_dump($result);
ps: I am working with the yii2 framework
so can anyone tell me what is wrong?
{
"client": {
"baseUrl": null,
"formatters": {
"urlencoded": {
"encodingType": 1,
"charset": null
}
},
"parsers": [],
"requestConfig": [],
"responseConfig": {
"format": "json"
},
"contentLoggingMaxSize": 2000
}
}
that is the error I am getting. I don't get any details regarding the connection ...
this worked for me
$client = new \yii\httpclient\Client(['responseConfig' => [
'format' => \yii\httpclient\Client::FORMAT_JSON,
]]);
$response = $client->createRequest()
->setHeaders(['authorization' => 'f52d76cc976e0e1b6aa81c926cbc33823b5e5983', 'content-type' => 'application/json'])
->setMethod('GET')
->setUrl('https://preprod-next-ngcvin5.ngc-data.fr/api/v1/vehicules/CR-157-NB')
->send();
return $response->data;
I'm trying to use ZohoMail's API to send email through my application. But it keeps giving me:
"{errorCode":"INVALID_METHOD"},"status":{"code":404,"description":"Invalid Input"}}
Here's the link to the Call that I'm trying to make: https://www.zoho.com/mail/help/api/post-send-an-email.html#Request_Body
Here's my function:
public static function sendEmail ($AccountId, $AuthCode, $FromAddress, $ToAddress, $Subject, $Content){
$client = new Client(); //GuzzleHttp\Client
$URI = 'http://mail.zoho.com/api/accounts/' . $AccountId . '/messages';
$headers = ['Content-Type' => 'application/json', 'Authorization' => 'Zoho-authtoken ' . $AuthCode];
$body = array('fromAddress' => $FromAddress, 'toAddress' => $ToAddress, 'subject' => $Subject, 'content' => $Content);
$Nbody = json_encode($body);
$response = $client->post($URI, $headers, $Nbody);
echo "DONE!";
}
I've tried changing the way I'm making the call but it doesn't seem like that's the problem. I've tested the call in PostMan and it works fine so there is probably something wrong with the way I'm making the call. Any help would be much appreciated.
You need to create data and headers in the same array and pass as a second argument. Use like this.
$client = new Client();
$URI = 'http://mail.zoho.com/api/accounts/'.$AccountId.'/messages';
$params['headers'] = ['Content-Type' => 'application/json', 'Authorization' => 'Zoho-authtoken ' . $AuthCode];
$params['form_params'] = array('fromAddress' => $FromAddress, 'toAddress' => $ToAddress, 'subject' => $Subject, 'content' => $Content);
$response = $client->post($URI, $params);
echo "DONE!";
Good Luck!
$client = new \GuzzleHttp\Client();
$response = $client->post(
'url',
[
GuzzleHttp\RequestOptions::JSON =>
['key' => 'value']
],
['Content-Type' => 'application/json']
);
$responseJSON = json_decode($response->getBody(), true);
$this->clients = new Client(['base_uri' => 'Url', 'timeout' => 2.0]);
$params['headers'] = ['Content-Type' => 'application/json'];
$params['json'] = array(
'parama1'=>$req->parama1,
'parama1'=>$req->parama2,
'parama3'=>$req->parama3,
);
$response = $this->clients->get('SearchBiz',$params);
$business = $response->getBody();
return View("myviewbiz")->with('business',json_decode($business));
Ty to use:
$response = $client->post($URI, $headers, ['json' => $body]);
instead of
$Nbody = json_encode($body);
$response = $client->post($URI, $headers, $Nbody);
After testing with cURL, I found that the URL had been 'moved' to https instead of http. Using just http, the call was going through in Postman but not with Guzzle. The only change I made was to make the URL:
https://mail.zoho.com/api/accounts/
The website lists it as just http and the request does go through with PostMan. I have made prior calls with just http in Guzzle from the same API and they went through. If someone could help me understand why this happened and why this specific call when using http works in PostMan and not in Guzzle, that'd be great.
This works anywhere place
use GuzzleHttp\Client;
$client = new Client();
$options = [];
$options['form_params'] = $data;
$options['http_errors'] = false; // for get exception y api response
$options['timeout'] = 5; // milliseconds
$client->request('PUT', $uri , $options);
$client = new Client();
$url = 'api-url';
$request = $client->post($url, [
'headers' => ['Content-Type' => 'application/json'],
'json' => ['token' => 'foo']
]);
return $request;
And I get back 502 Bad Gateway and Resource interpreted as Document but transferred with MIME type application/json
I need to make a POST request with some json. How can I do that with Guzzle in Laravel?
Give it a try
$response = $client->post('http://api.example.com', [
'json' => [
'key' => 'value'
]
]);
dd($response->getBody()->getContents());
Take a look..
$client = new Client();
$url = 'api-url';
$headers = array('Content-Type: application/json');
$data = array('json' => array('token' => 'foo'));
$request = new Request("POST", $url, $headers, json_encode($data));
$response = $client->send($request, ['timeout' => 10]);
$data = $response->getBody()->getContents();
you can also try this solution. that is working on my end. I am using Laravel 5.7.
This is an easy solution of Make a POST Request from PHP With Guzzle
function callThirdPartyPostAPI( $url,$postField )
{
$client = new Client();
$response = $client->post($url , [
//'debug' => TRUE,
'form_params' => $postField,
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
]
]);
return $body = $response->getBody();
}
For Use this method
$query['schoolCode'] =$req->schoolCode;
$query['token']=rand(19999,99999);
$query['cid'] =$req->cid;
$query['examId'] =$req->examId;
$query['userId'] =$req->userId;
$tURL = "https://www.XXXXXXXXXX/tabulation/update";
$response = callThirdPartyPostAPI($tURL,$query);
if( json_decode($response,true)['status'] )
{
return success(["data"=>json_decode($response,true)['data']]);
}
I am sending this as a test to a test webserver, but the response although its a 201 which means it got it, it does not show the posted data I want to send:
<?php
$url = "https://jsonplaceholder.typicode.com/posts";
$client = \Drupal::httpClient();
$post_data = array('color' => 'red');
$response = $client->request('POST', $url, [
'form_params' => $post_data,
'verify' => false
]);
$body = $response->getBody();
dsm($body);
?>
Is the format of the request I made incorrect?
I can see that it is not getting the post data because when I do a dsm of the response body, it isn't there.
This worked for me, looks like I needed to add the headers:
$url="https://jsonplaceholder.typicode.com/posts";
$client = \Drupal::httpClient();
$post_data = $form_state->cleanValues()->getValues();
$response = $client->request('POST', $url, [
'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
'form_params' => $post_data,
'verify'=>false,
]);
$body = $response->getBody()->getContents();
$status = $response->getStatusCode();
dsm($body);
dsm($status);