Guzzle 6: Get URL that was "resolved" from base_uri - guzzle6

In Guzzle 3 you can get the resolved URL (without actually opening it) like this:
$client = new Client([
'base_uri' => 'http://foo.com',
]);
$request = $client->get('bar.html');
echo $request->getUrl();
In Guzzle 6 this is not working anymore. Is there another way to get "http://foo.com/bar.html"?

You can use the history middleware, works as advertised:
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Psr\Http\Message\RequestInterface;
$container = [];
$stack = HandlerStack::create();
$stack->push(Middleware::history($container));
$client = new Client([
'base_uri' => 'http://foo.com',
'handler' => $stack,
]);
$response = $client->request('GET', 'bar.html');
/* #var RequestInterface $request */
$request = $container[0]['request'];
echo $request->getUri();
For reference, see http://docs.guzzlephp.org/en/latest/testing.html#history-middleware.

It is a bit late, but for the reference.
You can do it with \GuzzleHttp\Psr7\UriResolver::resolve($baseUri, $relUri);
It converts the relative URI into a new URI that is resolved against the base URI.
$baseUri and $relUri are instances of \Psr\Http\Message\UriInterfaceUriInterface.

Related

How to Retrieve HTTP Status Code with Guzzle?

New to Guzzle/Http.
I have a API rest url login that answer with 401 code if not authorized, or 400 if missing values.
I would get the http status code to check if there is some issues, but cannot have only the code (integer or string).
This is my piece of code, I did use instruction here ( http://docs.guzzlephp.org/en/stable/quickstart.html#exceptions )
namespace controllers;
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\ClientException;
$client = new \GuzzleHttp\Client();
$url = $this->getBaseDomain().'/api/v1/login';
try {
$res = $client->request('POST', $url, [
'form_params' => [
'username' => 'abc',
'password' => '123'
]
]);
} catch (ClientException $e) {
//echo Psr7\str($e->getRequest());
echo Psr7\str($e->getResponse());
}
You can use the getStatusCode function.
$response = $client->request('GET', $url);
$statusCode = $response->getStatusCode();
Note: If your URL redirects to some other URL then you need to set false value for allow_redirects property to be able to detect initial status code for parent URL.
// On client creation
$client = new GuzzleHttp\Client([
'allow_redirects' => false
]);
// Using with request function
$client->request('GET', '/url/with/redirect', ['allow_redirects' => false]);
If you want to check status code in catch block, then you need to use $exception->getCode()
More about responses
More about allow_redirects
you can also use this code :
$client = new \GuzzleHttp\Client(['base_uri' 'http://...', 'http_errors' => false]);
hope help you

slim Guzzle to psr http. for slim PhpRenderer view

$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'http://127.0.0.1/slim_project/getall',
array(
'headers' => array(
'Authorization' => "Bearer fghfghfgh-sdfsdfs-sdfsdf}",
)
)
);
$data = $response->withBody($res->getBody());
return $this->renderer->render($data->getBody(), 'pages/tables.php');
When i run the code. i got this error.
Argument 1 passed to Slim\Views\PhpRenderer::render() must implement interface Psr\Http\Message\ResponseInterface, instance of GuzzleHttp\Psr7\Stream given, called in /var/www/html/slim_project/index.php on line 101 and defined
How Can i convert Guzzle to psr/http\message. That how can i use this.
Thanks in advance.
return $this->renderer->render($response, 'pages/tables.php', json_decode($data->getBody(), true));

How to get the query parameters in a Guzzle/ Psr7 request

I am using Guzzle 6.
I am trying to mock a client and use it like so:
<?php
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
$mock_handler = new MockHandler([
new Response(200, ['Content-Type' => 'application/json'], 'foo'),
]);
$history = [];
$history_middleware = Middleware::history($history);
$handler_stack = HandlerStack::create($mock_handler);
$handler_stack->push($history_middleware);
$mock_client = new Client(['handler' => $handler_stack]);
// Use mock client in some way
$mock_client->get("http://example.com", [
'query' => [
'bar' => '10',
'hello' => '20'
],
]);
// ------
// get original request using history
$transaction = $history[0];
/** #var Request $request */
$request = $transaction['request'];
// How can I get the query parameters that was used in the request (i.e. bar)
My question is how can I get the query parameters used in the GuzzleHttp\Psr7\Request class?
The closest I managed to get is the following: $request->getUri()->getQuery(), but this just returns a string like so: bar=10&hello=20.
I seem to have solved my problem.
I can simply do this:
parse_str($request->getUri()->getQuery(), $query);
and I now have an array of the query parameters.
Other solutions are welcome!

Authorization http header is not working at Zend Soap Client

I Used the below code to retrive the categories from the third party site using API, but unfortunately stream context is not able to requested at their API and resulting in the Internal Error.
FYI : It is used under zend framework.
$header = "Authorization: Bearer ".$accestoken."\r\n"."Content-Type:text/xml";//.'Content-Type:application/xml';
$wsdl = 'wsdl url';
$context = stream_context_create(array('http' => array('header' => $header,'method'=>'GET')));
$options = array('stream_context'=>$context,'encoding'=>'ISO-8859-1','exceptions'=>FALSE);
$params = array ('accessToken' => $accestoken);
$response = $client->getAdCategories($params);
print_r($response);
So please find the above code and provide some solution for this issue.
$httpHeaders = array(
'http'=>array(
'protocol_version' => 1.1,
'header' => "Authorization:Bearer ".$accestoken."\r\n" ,
"Connection: close"
));
$context = stream_context_create($httpHeaders);
$soapparams = array(
'stream_context' => $context,
);
$client = new SoapClient($wsdl, $soapparams);
$response = $client->getAdCategories($params);
print_r($response);
Please refer https://bugs.php.net/bug.php?id=49853
OK, I see in the title at least this is a SOAP service you are trying to work with. You should then be using something like the Zend_Soap_Client.
Looks like you have a WSDL... so,
$client = new Zend_Soap_Client("yourwsdl.wsdl");
and then make a request like
$retval = $client->method1(10);
Looking at your code I am not 100% sure what authentication approach is in use. If basic HTTP auth you can just pass username and password as options in the client's constructor.
Setting a header might look something like this:
$auth = new stdClass();
$auth->user = 'joe';
$auth->token = '12345';
$authHeader = new SoapHeader('authNamespace', 'authenticate', $auth);
$client->__setSoapHeaders(array($authHeader));
If you need more help post your WSDL.

Getting Response Body using Zend_http_Client

I am succesfully calling a REST API with the following code
$client = new Zend_Http_Client();
$client->setMethod(Zend_Http_Client::POST);
$client->setUri('http://www.example.com/api/type/');
$client->setParameterPost(array(
'useremail' => '******#*****.***',
'apikey' => 'secretkey',
'description' => 'TEST WEB API',
'amount' => '5000.00'
));
However I would like to get both the header value-(201) and Response Body that are returned after the execution.
How do I proceed with that?
I am assuming that you're actually executing the request via:
$response = $client->request();
At that point all you need is in the $response object,
//Dump headers
print_r($response->headers);
//Dump body
echo $response->getBody();
Refer to the Zend_Http_Response docs at:
http://framework.zend.com/apidoc/1.10/
for more methods that are available.
this should work...
$client->setUri ( $image_source_urls );
$response = $client->request ( 'GET' );
$folder_content = $response->getBody ();