7

Create HTTP requests to communicate with other websites in laravel

 2 years ago
source link: https://www.laravelcode.com/post/create-http-requests-to-communicate-with-other-websites-in-laravel
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Create HTTP requests to communicate with other websites in laravel

  1741 views

  8 months ago

Laravel

Larave is adding new features to its new versions and improving day by day. With the new Laravel version, there are lots of new features are added. In the latest version, Laravel has added expressive, minimal API to create guzzleHTTPrequest.

In this article, we will discuss on how to make http request to other websites using guzzle in Laravel. Laravel has introduced new facade Http which makes guzzleHttp request. With Http facade, you can use get, post, put, patch, and deete method.

Laravel uses Guzzle package to create request and By default, automatically included as dependency. You can also install Guzzle by composer.

composer require guzzlehttp/guzzle

So lets get into this with example.

Create simple get request.

First of all, make basic get request with bellow code. Don't forget to use Http facade.

use Illuminate\Support\Facades\Http;

$response = Http::get('http://laravelcode.com');

The get method will return an instance of Illuminate\Http\Client\Response, which allows to call many method to get data.

$response->body() : string;
$response->json() : array;
$response->status() : int;
$response->ok() : bool;
$response->successful() : bool;
$response->serverError() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;

So if you want to get html code of https://hackthestuff.com, just create new get request as bellow. It will return as string data.

use Illuminate\Support\Facades\Http;

$response = Http::get('https://laravelcode.com');
$response_html = $response->body();

Send request with data

You may also create post, put or patch method with additional data. By default, data will be sent as application/json content type:

$response = Http::post('https://laravelcode.com/1/comment/create/', [
    'name' => 'Steve',
    'body' => 'Thank you very much',
]);

If you want to send data as application/x-www-form-urlencoded  content type request instead of application/json content type, use asForm() method instead of post() method.

$response = Http::asForm('https://laravelcode.com/1/comment/create/', [
    'name' => 'Steve',
    'body' => 'Thank you very much',
]);

Send request with file

You may also want to send file with request. Call attach() method before calling request. The attach() method accepts two required parameters, name of the file and content of file.

$response = Http::attach(
    'profile', file_get_contents('photo.jpg'), 'photo.jpg'
)->post('https://laravelcode.com/users/1/update');

Add headers

To add more headers to request, attach withHeaders() method before request call.

$response = Http::withHeaders([
    'private_key' => '7YlIdcrjMt9qFU29klgonl4s5gd5sbsd578g'
])->post('https://laravelcode.com/users/3/update', [
    'name' => 'John',
]);

Authorization

If your request needs authorization, you may specify basic and digest authentication credentials using the withBasicAuth and withDigestAuth methods.

Basic authentication

$response = Http::withBasicAuth('[email protected]', 'password')->post('https://hackthestuff.com/user/get-details');

Digest authentication

$response = Http::withDigestAuth('[email protected]', 'password')->post('https://hackthestuff.com/user/get-details');

Bearer Tokens

If request need to add Authorization of bearer token in header, you can simply attach withToken() method.

$response = Http::withToken('v58sfsef8bsd24wf5sefs8fgvsds
')->post('https://laravelcode.com/user/get-details');

Timeout request

You may add timeout() method to wait for request for specified number of seconds.

$response = Http::timeout(10)->get('https://hackthestuff.com');

After timeout, an instance of Illuminate\Http\Client\ConnectionException will be thrown.

Retries

If you need to create automatic retries, you may add retry() method. The retry() method accepts two parameters, number of times request retries and number of milliseconds wait for new request.

$response = Http::retry(5, 100)->post('https://laravelcode.com/user/get-details');

After all requests failed, an instance of Illuminate\Http\Client\RequestException will be thrown.

Error handling

You can check if request returned with any error.

The successful() method will return true if request is ok.

$response->successful();

The clientError() method will return true if there is client side error occured.

$response->clientError();

The serverError() method will return true if there is server error occured.

$response->serverError();

If you want to throw error response, use throw() method.

$response = Http::post('https://laravelcode.com/user/get-details');
$response->throw();

This way you can create request in Laravel application. If you have any suggetion or question, please write in the bellow comment section.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK