Getting different status code using Laravel PHPUnit - laravel-5

Laravel 5.0
PHPUnit 4.8.24
If I visit my homepage route('/') in browser chrome shows me status-code 200 OK
But when I check with PHPUNIT
$response = $this->call( 'GET', '/' );
var_dump( $response->getStatusCode() );
It returns int(500) why?

There might be multiple reasons for that for example incorrect database connection. You should run:
$response = $this->call( 'GET', '/' );
var_dump($response->getContent());
or verify error log to see what's the exact problem

Related

Get cookies from Laravel Http Client

I'm trying to login into a service (Jasper Server API) using the Http Client, but cant get the cookies from the response
This is what I'm doing:
$response = Http::withOptions( [ 'proxy' => '' ] )->
post('192.168.52.84/jasperserver/rest_v2/login?j_username=user&j_password=password');
$cookies=$response->cookies;
dd($cookies);
The output being:
GuzzleHttp\Cookie\CookieJar {
-cookies: []
-strictMode: false
}
When I do the same Get on the browser I get the cookies fine.
What could be the problem?
You can get cookie value by the following code also, get cookie by name and then get the value.
$cookies = $response->cookies()->getCookieByName('YOUR_COOKIE_NAME')->getValue();
I finally solved it.
It was just that when I did:
post('192.168.52.84/jasperserver...')
I didn't specify the scheme:
post('http://192.168.52.84/jasperserver...')
With that, I got the cookies just right.

Force response()->download() return HTTPS url

I have switched my Laravel 5.1 to HTTPS and everything seems fine, except the file download part.
The problem is response()->download() returns a HTTP link instead of HTTPS and I get a mixed content in Chrome, so the link is blocked.
And some code:
$headers = array
(
'Content-Type' => 'application/vnd.android.package-archive'
);
return response()->download(config('custom.storage') . $apk->generated_filename, $apk->filename, $headers);

How to retrieve JSON from a API endpoint using Laravel 5.4?

I have 2 projects made with Laravel 5.4:
Prj-1 it is an Restful API that returns JSON.
Prj-2 it is an website that consumes the above endpoints.
In this way, I have the follow endpoint from Prj-1 :
myAPI.com/city that returns a list of all cities in the database in a JSON format.
Inside Prj-2 I have the follow:
Route:
Route::get('/showCityAPItest','AddressController#getcity');
Controller:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
...
public function getcity()
{
$request =Request::create('http://myAPI.com/city', 'GET');
$response = Route::dispatch($request);
dd($response);
}
If I use directly the URL (http://myAPI.com/city) in the browser, it works. I can see the JSON as expected.
BUt when I try to retrieve it from the Prj-2 I can't see it in the browser.
Actually I see
404 Not Found
nginx/1.10.1 (Ubuntu)
I was following this post but I dont know what am I doing wrong.
Any help?
Yeah, #Joel Hinz is right. Request will work within same project api end.
You need to use GuzzleHttp.
Step 1. Install guzzle using composer. Windows base operating guzzle command for composer :
composer require guzzlehttp/guzzle
step 2 write following code
public function getcity()
{
$client = new \GuzzleHttp\Client;
$data =$client->request('GET', 'http://myAPI.com/city', [
'headers' => [
'Accept' => 'application/json',
'Content-type' => 'application/json'
]
]);
$x = json_decode($data->getBody()->getContents());
return response()->json(['msg' => $x], 200);
}
The answer to which you are referring is talking about internal routes. You can't use the Request and Route facades for external addresses like that. Instead, use e.g. Guzzle (http://docs.guzzlephp.org/en/latest/) to send your requests from the second site.

How to use Guzzle on Codeigniter?

I am creating a web application on Codeigniter 3.2 which works with the Facebook Graph API. In order to make GET & POST HTTP requests, I need a curl library for Codeigniter. I have found Guzzle but I Don't know how to use Guzzle on Codeigniter.
Check this link:
https://github.com/rohitbh09/codeigniter-guzzle
$this->load->library('guzzle');
# guzzle client define
$client = new GuzzleHttp\Client();
#This url define speific Target for guzzle
$url = 'http://www.google.com';
#guzzle
try {
# guzzle post request example with form parameter
$response = $client->request( 'POST',
$url,
[ 'form_params'
=> [ 'processId' => '2' ]
]
);
#guzzle repose for future use
echo $response->getStatusCode(); // 200
echo $response->getReasonPhrase(); // OK
echo $response->getProtocolVersion(); // 1.1
echo $response->getBody();
} catch (GuzzleHttp\Exception\BadResponseException $e) {
#guzzle repose for future use
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
print_r($responseBodyAsString);
}
You can integrate Guzzle into Codeigniter 3.x by following the following steps:
NOTE: I was doing this on Windows, should work on other platforms too.
Open the command terminal on your computer
Change directory to your Codeigniter app installation (i.e. my app is called MyCodeigniterApp)
cd C:\wamp64\www\MyCodeigniterApp
Install Composer in that directory by running the following command on the terminal
curl -sS https://getcomposer.org/installer | php
After installing Composer, we can now install Guzzle by running the following command on the terminal
composer require guzzlehttp/guzzle
if you encounter the following error while executing the above command
follow the recommendation in the error message.
Open composer.json located in your App root folder i.e. C:\wamp64\www\MyCodeigniterApp
then change
"mikey179/vfsStream": "1.1.*"
to
"mikey179/vfsstream": "1.1.*"
You can now re-run the command in step 4 to install Guzzle
After successful installation of Guzzle, you now need to make the following changes to the config.php file under the application/config directory
make the following changes under Composer auto-loading section and let the configuration be:
$config['composer_autoload'] = 'vendor/autoload.php';
The integration is complete, now you can use Guzzle in your controllers or models as below or by following the guides from Guzzle documentation on https://docs.guzzlephp.org/en/stable/
//Create guzzle http client
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type')[0];
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
DONE.......

how to integrate sabredav in laravel controller?

I'm trying to create a SabreDAV-Server in a Laravel Route. The following Code shows that I tried:
Illuminate\Routing\Router::$verbs = [
'GET',
'HEAD',
'POST',
'PUT',
'PATCH',
'DELETE',
'PROPFIND',
'PROPPATCH',
'MKCOL',
'COPY',
'MOVE',
'LOCK',
'UNLOCK'
];
Route::match(['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'PATCH', 'PROPFIND', 'PROPPATCH', 'MKCOL', 'COPY', 'MOVE', 'LOCK', 'UNLOCK'], 'carddav{test}', function()
{
date_default_timezone_set('Europe/Berlin');
$baseUri = '/carddav';
$pdo = new PDO('mysql:host=localhost;dbname=dav', 'root', 'root');
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$authBackend = new \Sabre\DAV\Auth\Backend\PDO($pdo);
$principalBackend = new \Sabre\DAVACL\PrincipalBackend\PDO($pdo);
$carddavBackend = new \Sabre\CardDAV\Backend\PDO($pdo);
$nodes = [
new \Sabre\DAVACL\PrincipalCollection($principalBackend),
new \Sabre\CardDAV\AddressBookRoot($principalBackend, $carddavBackend)
];
$server = new \Sabre\DAV\Server($nodes);
$server->setBaseUri($baseUri);
$server->addPlugin(new \Sabre\DAV\Auth\Plugin($authBackend, 'SabreDAV'));
$server->addPlugin(new \Sabre\DAV\Browser\Plugin());
$server->addPlugin(new \Sabre\CardDAV\Plugin());
$server->addPlugin(new \Sabre\DAVACL\Plugin());
$server->addPlugin(new \Sabre\DAV\Sync\Plugin());
$server->exec();
})->where('path', '(.)*';
But if I try to call it in the Browser there is an error:
<?xml version="1.0" encoding="utf-8"?>
<d:error xmlns:d="DAV:" xmlns:s="http://sabredav.org/ns">
<s:sabredav-version>2.0.4</s:sabredav-version>
<s:exception>Sabre\DAV\Exception\NotAuthenticated</s:exception>
<s:message>No digest authentication headers were found</s:message>
</d:error>
There was no authentication prompt.
If I try to connect from Evolution there was the message: "Method Not Allowed".
Has someone any idea what the problem is?
Thanks,
pepe
The problem is the sent HTTP status code. No matter the response from SabreDAV, the Laravel router always sets the HTTP status code to 200, so no CardDAV client will ever know they have to authorize requests – ignoring the Basic Auth Challenge.
My solution might not be the most elegant one, but it is working. Just wrap the $server->exec() in ob_start() and ob_end() tags and output the content with a real Laravel response:
ob_start();
$server->exec();
$status = $server->httpResponse->getStatus();
$content = ob_get_contents();
ob_end_clean();
return response($content, $status);
General guidance:
Use "postman" (Google Chrome App) to test requests, you'll see they are working when sending authorization headers upfront
Use a web debugging proxy like "Charles" to monitor actual request and response bodies

Resources