Guzzle 6.0 download file using request headers - download

I can't find any example of how to download a remote file using Guzzle 6.0. I need to pass headers in the GET request.
I have looked at the documentation which isn't helpful at all.
I came up with this but it still doesn't download a file
require_once('vendor/autoload.php');
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
$client = new Client();
$response = $client->request('GET', '/stream/20', [
'headers' => [
'Authorization: Token token' => 'df456g4fd564gfs65dg45s6fdg4dsf5g4sd65g',
'Cache-Control' => 'no-cache',
'Content-Type' => 'application/pdf'
],
'sink' => 'https://example.com/path/to/file',
]);
Has anyone successfully downloaded a file using request headers?

I think you got confused.
Where you have '/stream/20' is the url of where the file is you want to download.
The sink part is where you want to save your image.
Try this....
require __DIR__ . '/vendor/autoload.php';
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
$client = new Client();
$resource = fopen('test.pdf', 'w');
$response = $client->request('GET', 'https://example.com/path/to/file', [
'headers' => [
'Authorization' => 'Token token=df456g4fd564gfs65dg45s6fdg4dsf5g4sd65g',
'Cache-Control' => 'no-cache',
'Content-Type' => 'application/pdf'
],
'sink' => $resource,
]);
echo 'downloaded';

Related

Getting cURL error 61 and no response for discover.search.hereapi.com/v1/discover endpoint

We are using https://discover.search.hereapi.com/v1/discover to perform a free-form text query for a latitude, longitude center.
Example: https://discover.search.hereapi.com/v1/discover?q=cafe+in+harrow&at=51.52236%2C-0.13993
The code block in PHP is
`$headers = [
'Authorization' => 'Bearer ' . $token,
'Accept' => 'application/json',
];
$client = new Client();
$response = $client->request($method, $url, [
'headers' => $headers
]);`
Now the problem is sometimes this endpoint do not return response due to cURL error 61
Error while processing content unencoding: incorrect header check (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
When this happen we have to change the code to
`$headers = [
'Authorization' => 'Bearer ' . $token,
'Accept' => 'application/json',
];
$client = new Client();
$response = $client->request($method, $url, [
'headers' => $headers,
'decode_content' => 'gzip'
]);`
After adding 'decode_content' => 'gzip' it works.
But again after some days it stop working and then we have to remove this 'decode_content' => 'gzip' line
Please guide us how to solve this issue?

UnauthorizedError: No authorization token was found with Laravel 8

I'm trying to make a GET request passing a bearer token as authentication.
I try to pass the token with:
$response = Http::get($url, [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Accept' => 'application/json',
],
]);
as stated in the docs
When I check the value of the variables, I get:
$token : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDc0NTI0NzksInVzZXJuYW1lIjoic3VuY2hhaW4iLCJvcmdOYW1lIjoib3JnMCIsImlhdCI6MTYwNzQxNjQ3OX0.LUTFZh8Em13f3cQ8TpxgayVRC9XvVHyczOhQXARxk48"
$url : "https://example.com/channels/common/chaincodes/main?peer=org0/peer0&args=%5B%222020-12-01T22%3A00%3A00Z%22%2C+%222020-12-01T22%3A30%3A00Z%22%5D&fcn=GetMeasuresBetween"
But when I copy paste those values in Postman, GET is working and I can get my data, which means data is correct, and the way I execute my GET request might be incorrect.
Where am I wrong ? It seems all good to me !
I found the solution,
$response = Http::withToken($token)->get($url, [
'headers' => $headers,
'peer' => $this->peer,
'args' => $arrayArgs,
'fcn' => "GetMeasuresBetween",
]);
Or, you may use guzzle, and initialize
$client = new \GuzzleHttp\Client(['base_uri' => $this->url]);
$response = $client->request('GET', $url, [
'headers' => $headers,
'peer' => $this->peer,
'args' => $arrayArgs,
'fcn' => "GetMeasuresBetween",
]);
I don't know why it is not working the first way, but it is now working !

laravel guzzle httpsocket parameters for ssl verify peer & host

I have the following code in CakePHP. I need the same code in laravel using guzzle
$url = "https://xyz?";
$query ='first_name='. $data->FirstName .'&gender=""'. '&home_phone='. $data->HomePhone.'&ip_address='. $data->IPAddress.'&last_name='. $data->LastName.'&user_defined_url='. $result;
$HttpSocket = new HttpSocket(array('ssl_verify_peer' => false, 'ssl_verify_host' => false));
$post_response = $HttpSocket->get($url,$query);
$response = explode('&',$post_response->body);
I have converted it in laravel using guzzle but doesnt work. Following my code that Ive converted in laravel:
$client = new Client(['verify' => false ]);
$post_response = $client->get($url, $query);
$response = explode('&',$post_response->body);
Note: use GuzzleHttp\Client; is written at the top of file.
Thanks in advance for the help!
Can you try like this,
$client = new Client();
$post_response = $client->request('GET', $url, [
'verify' => false,
'form_params' => [
'first_name' => $data->FirstName,
'gender' => "",
'home_phone' => $data->HomePhone,
'ip_address' => $data->IPAddress,
'last_name' => $data->LastName,
'user_defined_url' => $result
]
]);
$response = explode('&',$post_response->body);
Instead of form_params you can use query for sending the parameters as query string.

Headers get written to file after uploading with Guzzle

I'm trying to upload a csv file to a cloud storage using Laravel and Guzzle. The file does get successfully uploaded, but the problem is that for some reason the headers are written to the file along with the original content after the upload. That also happens when I upload the file through Postman. How can this be prevented and what is the correct way of sending such request ? Here's the snippet and the uploaded file content :
$res = $client->request('POST', $uri, [
'headers' => [
'Authorization' => 'Bearer '. $egnyteToken,
'Content-Type' => 'text/csv'
],
'multipart' => [
[
'name' => $file->getClientOriginalName(),
'contents' => File::get($file),
'filename' => $file->getClientOriginalName(),
]
]
]);
Seems that the server doesn't require multipart body, so because of this you see all content that you sent in the uploaded file.
Just use body and not multipart.
$res = $client->request('POST', $uri, [
'headers' => [
// ...
],
'body' => File::get($file),
]);

Testing AJAX/XMLHttpRequest pages functionally in Symfony2

Is it possible to simulate/make an XMLHttpRequest request (ajax) in symfony2 tests?
After search with "Problematic" answer, the correct syntax is:
$crawler = $client->request('GET', '/foo/', array(), array(), array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
));
The Request#isXmlHttpRequest() method simply checks if the X-Requested-With header is equivalent to XMLHttpRequest. If that's the method you're using to determine if a request is an ajax call, then you can simulate the behavior in the test client by adding the appropriate header to the request:
class FooFunctionalTest extends WebTestCase
{
$client = static::CreateClient();
$crawler = $client->request('GET', '/foo/', array(), array(), array(
'X-Requested-With' => 'XMLHttpRequest',
));
// ...
}
More information can be found about the Request object in the source code.
For POST, PUT:
$crawler = $client->request('POST', '/foo/', array('param' => 'value'), array(),
array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
));
For POST, PUT with raw JSON body:
$crawler = $client->request('POST', '/foo/', array(), array(), array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
'CONTENT_TYPE' => 'application/json',
), '{"param": "value"}');
If you are working with Symfony 3.x or 4.x this is the correct way to do it using POST method.
$data = ['some' => 'value'];
$client = static::createClient();
$client->request('POST', '/some_uri', ['data' => $data], [],; [
'HTTP_X-Requested-With' => 'XMLHttpRequest',
]);

Resources