Sending a custom header with ZEND_HTTP_CLIENT - php

How can I send a custom header with the ZEND_HTTP_CLIENT. I am trying to send a variable key with a certain value, that I will check later for authenticity
I've tried this
$client = new Zend_Http_Client('http://localhost/v3/files/');
$client->setHeaders('Content-type','multipart/form-data');
$client->setHeaders('key','XXXxXXXXXXXXXXXXXX');
$client->setParameterPost('document_id', $id);
$client->setParameterPost('type_id', $docType['type']);
$client->setParameterPost('file', $form->file);
$response = $client->request(Zend_Http_Client::POST);
and this
$client = new Zend_Http_Client('http://localhost/v3/files/');
$client->setHeaders(array(
'Content-type','multipart/form-data',
'key','XXXxXXXXXXXXXXXXXX'));
$client->setParameterPost('document_id', $id);
$client->setParameterPost('type_id', $docType['type']);
$client->setParameterPost('file', $form->file);
$response = $client->request(Zend_Http_Client::POST);
but it doesnt seem to work. It says key is not a valid type.
I want to send a custom header like this (similar to what happens when you set headers with the Postman client).
Is this possible?

Try with add a config param like this:
$client = new Zend_Http_Client('http://localhost/v3/files/', array('strict' => false));

Related

Set request content to test in symfony

I have to set a test to check the user registragion with an API , but I'm not sure how to set the content, its has to had a header with the token named x-auth-tokenand the body with aform-data` param named data that contains json-string
public function testUserRegister(){
$client = static::createClient();
$server = array('x-auth-token' => '...');
$client->request(Request::METHOD_POST, self::$uri, [], [], $server);
$response = $client->getResponse();
self::assertEquals( Response::HTTP_CREATED, $response->getStatusCode());
}
When I check on the debug ther is no x-auth-token on the headers
Use third parameter of $client->request method to pass your data.
If you want to send payload as form data with JSON, you need to do something like this:
$client->request(..., ..., ['data' => json_encode(...)], ...);
Keep in mind that you maybe need to set correct Content-Type in header (application/x-www-form-urlencoded).

How to get GuzzleHttp 7.x resolved request url from response

How to get the URI/URL of the request sent, from the response?
<?php
// Create a client with a base URI
$client = new GuzzleHttp\Client(['base_uri' => 'https://example.com/api/']);
// Send a request to https://example.com/api/test
$response = $client->request('GET', 'test');
// I want the following line to print 'https://example.com/api/test'
var_export( $response->getUrl() );
Note: I want something like the last line of the above snippet to work.

How to upload a file using zend HttpClient?

I'm using HTTP client. How to attach a file while sending a post request?
Here's my code:
function executePost($postdata = [], $full_file_path = ''){
self::$client = new Zend\Http\Client(null,
['timeout' => 30] // updated to 30 sec
);
self::$client->setEncType(Zend\Http\Client::ENC_URLENCODED);
self::$client->setUri($url);
self::$client->setMethod($method);
self::$client->setParameterPost($postdata);
$response = $client->send();
Debug::dump($response->getContent(),$label='Response',$echo=true);
}
I have tried $postdata['file_contents'] = '#'.$full_file_path; but it doesn't help.
Does anyone have an idea on how to attach file with the post data?
Thanks in advance.
Instead of using that data array try using the designated method called setFileUpload. So in your example it could look like so:
$client = new \Zend\Http\Client(null, ['timeout' => 30]);
$client->setUri($url);
$client->setFileUpload($full_file_path, 'file_contents');
$client->setMethod('POST'); // this must be either POST or PUT
$response = $client->send();
setFileUpload should also set the enc type.
There's a doc section related to that here.

How to add form data on Post requests for Buzz HTTP Client on Laravel?

I'm using Buzz HTTP Client for Laravel.
I have a problem adding form data to my POST requests, since it wasn't specified in it's wiki/documentation.
Listed below are the two ways of sending requests.
Example 1:
$response = Buzz::post('http://api.website.com/login');
//how do I add a "username", and "password" field in my POST request?
echo $response;
echo $response->getContent;
Example 2:
$request = new Buzz\Message\Request('POST', '/', 'http://google.com');
$response = new Buzz\Message\Response();
//how do I add a "username", and "password" field in my POST request?
$client = new Buzz\Client\FileGetContents();
$client->send($request, $response);
echo $request;
echo $response;
The answer here is going to really depend on what the API expects. Lets assume, the API expects the password and username sent as JSON in the content of the request. The example http request would look something like:
POST /login HTTP/1.1
Content-Type: application/json
{
"username": "bugsBunny",
"password": "wh4tsUpD0c"
}
To do this with Buzz, this should work:
$jsonPayload = json_encode([
‘username’ => ‘bugsBunny’,
‘password’ => ‘wh4tsUpD0c
]);
$headers = ['Content-Type', 'application/json'];
$response = Buzz::post('http://api.website.com/login', $headers, $jsonPayload);
If you're attempting to submit a form on a given website, you shouldn't use the above method. Instead use Buzz's built in form method which will attach the correct headers.
use Buzz\Message\Form;
$request = new Form(Form::METHOD_POST, ‘login’, ‘api.website.com’);
$request->setFields([
‘username’ => ‘bugsBunny’,
‘password’ => ‘wh4tsUpD0c’
]);
$response = new Buzz\Message\Response();
$client = new Buzz\Client\Curl();
$client->send($request, $response);
On a side note, I'd suggest not using this library. The library is, as you stated, Laravel integration for Buzz. The issue here is, the author should have made buzz a dependency listed in composer, rather than include the Buzz source directly. This prevents updates to Buzz from making their way into this project. You can see on the actual Buzz repo, the last commit was 29 days ago. Also if another package is using Buzz and including it correctly by composer, composer would install both packages. But when an instance of Buzz was created, you couldn't be certain which version was being loaded. You should just use Buzz, which can be found on packagist.
// assuming $headers and $jsonPayload are the same as in previous example.
$browser = new Buzz\Browser();
$response = $browser->post('http://api.website.com/login', $headers, $jsonPayload);
It was foolish of me to not read the code first before asking.
The form data is actually pased on the third parameter for the function. Though it accepts strings only so don't forget to json encode your data.
Buzz Class
public function post($url, $headers = array(), $content = '')
{
....
....
}
Buzz::post($url, array(), json_encode(array('Username'=>'usernamexx','Password'=>'p#$$w0rD')) );

Guzzle cookies handling

I'm building a client app based on Guzzle. I'm getting stucked with cookie handling. I'm trying to implement it using Cookie plugin but I cannot get it to work. My client application is standard web application and it looks like it's working as long as I'm using the same guzzle object, but across requests it doesn't send the right cookies. I'm using FileCookieJar for storing cookies. How can I keep cookies across multiple guzzle objects?
// first request with login works fine
$cookiePlugin = new CookiePlugin(new FileCookieJar('/tmp/cookie-file'));
$client->addSubscriber($cookiePlugin);
$client->post('/login');
$client->get('/test/123.php?a=b');
// second request where I expect it working, but it's not...
$cookiePlugin = new CookiePlugin(new FileCookieJar('/tmp/cookie-file'));
$client->addSubscriber($cookiePlugin);
$client->get('/another-test/456');
You are creating a new instance of the CookiePlugin on the second request, you have to use the first one on the second (and subsequent) request as well.
$cookiePlugin = new CookiePlugin(new FileCookieJar('/tmp/cookie-file'));
//First Request
$client = new Guzzle\Http\Client();
$client->addSubscriber($cookiePlugin);
$client->post('/login');
$client->get('/test/first');
//Second Request, same client
// No need for $cookiePlugin = new CookiePlugin(...
$client->get('/test/second');
//Third Request, new client, same cookies
$client2 = new Guzzle\Http\Client();
$client2->addSubscriber($cookiePlugin); //uses same instance
$client2->get('/test/third');
$cookiePlugin = new CookiePlugin(new FileCookieJar($cookie_file_name));
// Add the cookie plugin to a client
$client = new Client($domain);
$client->addSubscriber($cookiePlugin);
// Send the request with no cookies and parse the returned cookies
$client->get($domain)->send();
// Send the request again, noticing that cookies are being sent
$request = $client->get($domain);
$request->send();
print_r ($request->getCookies());
Current answers will work if all requests are done in the same user request. But it won't work if the user first log in, then navigate through the site and query again later the "Domain".
Here is my solution (with ArrayCookieJar()):
Login
$cookiePlugin = new CookiePlugin(new ArrayCookieJar());
//First Request
$client = new Client($domain);
$client->addSubscriber($cookiePlugin);
$request = $client->post('/login');
$response = $request->send();
// Retrieve the cookie to save it somehow
$cookiesArray = $cookiePlugin->getCookieJar()->all($domain);
$cookie = $cookiesArray[0]->toArray();
// Save in session or cache of your app.
// In example laravel:
Cache::put('cookie', $cookie, 30);
Other request
// Create a new client object
$client = new Client($domain);
// Get the previously stored cookie
// Here example for laravel
$cookie = Cache::get('cookie');
// Create the new CookiePlugin object
$cookie = new Cookie($cookie);
$cookieJar = new ArrayCookieJar();
$cookieJar->add($cookie);
$cookiePlugin = new CookiePlugin($cookieJar);
$client->addSubscriber($cookiePlugin);
// Then you can do other query with these cookie
$request = $client->get('/getData');
$response = $request->send();

Categories