Getting Pending Request on HTTP Client Response while ataching multiple files - laravel

I am facing an issue while sending API requests to by HTTP Client. I am getting a Pending Request. How to fulfill the response and get the response data from $response->collect()
here is my code:
public function postMultipleFiles($url, $files, $params)
{
$response = Http::withHeaders([
'Authorization' => auth()->check() ? 'Bearer '.auth()->user()->api_token:''
]);
foreach($files as $k => $file)
{
$response = $response->attach('images['.$k.']', $file);
}
$response->post($this->base_url.$url, $params);
return response()->json($response->collect());
}
The error I am getting
message: "Method Illuminate\\Http\\Client\\PendingRequest::collect does not exist."

Related

How to do concurrent guzzle http post request to rest api in laravel?

I want to make concurrent Guzzle http requests in laravel to rest api i have users in 100k i want to perform billing for users.
Currently my guzzle http is doing synchronous calls to rest api which is taking 6 hours to complete 100k post requests and the requests does not have any call backs they are just post request with users msisdn and unique id in json format.
How to do concurrent 50 requests per second so that billing is performed quickly.
Following is part of my code which i use taken from https://docs.guzzlephp.org/en/stable/quickstart.html#concurrent-requests
$requests = function ($total) {
$url = "url here";
$auth = base64_encode($username . ":" . $password);
for ($i = 0; $i < $total; $i++) {
$msgdata =[
'msisdn'=>$msisdn,
$subscription
=>$subscriptionInfo];
yield new Request('post', $url,
[
'headers' =>
[
'Content-Type' => 'application/json',
'Authorization' => $authorizaton
],
'body' => json_encode($msgdata)
]);
}
$pool = new Pool($client, $requests(50), [
'concurrency' => 5,
'fulfilled' => function (Response $response, $index) {
// this is delivered each successful response
echo $response;
},
'rejected' => function (RequestException $reason, $index) {
// this is delivered each failed request
echo $reason;
},
]);
// Initiate the transfers and create a promise
$promise = $pool->promise();
// Force the pool of requests to complete.
$promise->wait();
i am getting response as
"status":401,"error":"Unauthorized"
But request params are not incorect idk why it is giving response as incorect
finally i found the solution to my problem, the problem was in request header and body parameters.
changed this
yield new Request('post', $url,
[
'headers' =>
[
'Content-Type' => 'application/json',
'Authorization' => $authorizaton
],
'body' => json_encode($msgdata)
]);
to
yield new Request('post', $url,
[
'Content-Type' => 'application/json',
'Authorization' => $authorizaton
],
json_encode($msgdata)
);

Transform CURL to Http facade laravel

I have this code :
$httpParams = [
'textData' => $content,
'xmlFile' => new \CurlFile($params['file']->getPathName())
];
$curlHandle = curl_init('http://url.com');
curl_setopt($curlHandle, CURLOPT_HEADER, false);
curl_setopt($curlHandle, CURLOPT_POST, true);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $httpParams);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
$curlResponse = curl_exec($curlHandle);
curl_close($curlHandle);
dump($curlResponse);die();
I have the response in $curlResponse with status = 200
But when I tried with Http from laravel :
$http = Http::asForm();
$httpParams = [
'textData' => $content,
'xmlFile' => new \CurlFile($params['file']->getPathName())
];
$response = $http->send('post', 'http://url.com', $httpParams)->body();
dump($response);
Response is empty : "". The status is 200. Can you help me please, why using Http facade I have empty response ? Thx in advance. Please help me !!!
You can write reusable method inside separate class
public function apiCall($url, $method = "get",$data=[])
{
$htppCall = Http::withHeaders([
'Content-Type' => 'application/json',
])->{$method}($url,$data);
if ($htppCall->status() == 401) {
//error handling
}
return $htppCall->object();
}
Then call like this
$httpParams = [
'textData' => $content,
'xmlFile' => new \CurlFile($params['file']->getPathName())
];
$response=$this->apiCall($url,'post',$httpParams);
dd($response);
Import right facade
use Illuminate\Support\Facades\Http;
checking what status code you got
$htppCall->status()
to get data as object
$htppCall->object()
To get data as array
$htppCall->json()
To check client errors
$htppCall->clientError()
to check server errors
$htppCall->serverError()
To Get the body of the response.
$htppCall->body()
If any issues let me know in comment

How to return response from async GuzzleHttp request to outer function or handle Exception in yii2?

I need to send async post request in background and save response (status code and request body to DB). I decide to use GuzzleHttp package (v6) for it.
The idea is run function sendAsyncRequest, send async request inside it, then get response from resource in array with keys code, data, return this array to outer function processAsyncRequest and then send it to function logResponse to save it to db.
use GuzzleHttp\Client as GuzzleClient;
class Logger
{
public function processAsyncRequest($client)
{
$response = $this->sendAsyncRequest($client->phone, ['utm_source' => $client->utm_source]);
$this->logResponse($client, $response);
}
public function sendAsyncRequest($phone, $params)
{
$url_params = http_build_query(['utm_source' => $client->utm_source]);
$guzzleClient = new GuzzleClient();
$headers = [
'Content-Type' => 'application/json',
'Authorization' => 'Basic xxxxxxxxxx',
];
$request = new Request('POST', 'url' . $phone . '/tokens/?' . $url_params, $headers);
$promise = $guzzleClient->sendAsync($request);
$promise->then(
function (ResponseInterface $response) {
return [
'code' => $response->getStatusCode(),
'body' => $response->getBody()->__toString(),
];
},
function(RequestException $e) {
return [
'code' => $e->getResponse()->getStatusCode(),
'body' => $e->getMessage(),
];
}
);
$res = $promise->wait();
return $res;
}
public function logResponse($client, $data)
{
$log = new Log();
$log->client_id = $client->id;
$log->url = 'url';
$log->response = $data['code'] . ', ' . $data['body'];
$log->comment = 'reg';
return $log->save();
}
}
The problems are:
function sendAsyncRequest returns object of GuzzleHttp\Psr7\Response, I see the error "Cannot use object of type GuzzleHttp\Psr7\Response as array" and I have no idea how to get my $res array from it.
how to correctly handle exception if promise will return error?

How to call a Java Rest API from PHP Codeigniter Controller?

I have a rest service written in Spring MVC. The requirement is to call the particular service from my Codeigniter project. Here is the code I used,
function connection(){
header('Access-Control-Allow-Origin: *');
$endpoint = "http://localhost:8090/{projectName}/{rest_endpoint}";
try
{
// Get cURL resource
$curl = curl_init();
// Set some options
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $endpoint,
CURLOPT_HTTPHEADER => ['Accept:application/json']
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Check HTTP status code
if (!curl_errno($curl)) {
switch ($http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE)) {
case 200: # OK
echo "Server JSON Response:" . $resp;
break;
default:
echo 'Unexpected HTTP code: ', $http_code, "\n";
echo $resp;
}
}
// Close request to clear up some resources
curl_close($curl);
} catch (Exception $ex) {
printf("Error while sending request, reason: %s\n",$ex->getMessage());
}
}
This does not call the Rest endpoint. Both of them are running on localhost.

Request to google calendar api

I create web application that will work with Google Calendar.
I use Guzzle for http requests.
I successfully authorized and got token.
I have some trouble when i tried to add event in some calendar.
$url = 'https://www.googleapis.com/calendar/v3/calendars/'. $calendar_id .'/events';
$client = new Guzzle\Http\Client();
$data = json_encode(array(
"end" => array("date" => "2015-04-02"),
"start" => array("date" => "2015-04-01"),
"summary" => "test3"
));
$request = $client->post($url, [], $data);
$request->setHeader('Authorization', $token_type . ' ' . $token);
$response = $request->send();
echo $response->getBody();
The response is
Client error response [status code] 400 [reason phrase] Bad Request [url] https://www.googleapis.com/calendar/v3/calendars/some_calendar/events
Please explain me what is wrong?
Thanks a lot!
I think you meant to do
use Guzzle\Http\Client;
$url = 'https://www.googleapis.com/calendar/v3/calendars/'. $calendar_id .'/events';
$client = new GuzzleClient($url);

Resources