Laravel CURL - Passing a string to HTTP URL (Postfields) - php

I use Laravel 9 and the built-in method Http::withHeaders ($headers)->post($url, $data).
In the $data variable, I pass the string that resulted from http_build_request with the "&" separator. But Laravel tries to make an array out of it and send data.
The API service returns me an error. Please tell me how you can force Laravel to pass exactly a STRING(!), and not an array?
My code:
$array = [
'key1' => 'value1',
'key2' => 'value2',
// etc...
];
$headers = [
'Content-Type' => 'application/x-www-form-urlencoded',
'HMAC' => $hmac
];
$data = http_build_query($array, '', '&');
$response = Http::withHeaders($headers)->post($api_url, $data);
return json_decode($response->getBody()));

If you sending it as x-www-form-urlencoded i gues u should be able to pass the data inside request body.
$response = Http::withHeaders($headers)
->withBody($data)
->asForm()
->post($api_url);
however, i am not sure if this will work

Have you tried, asForm?
$response = Http::withHeaders($headers)->asForm()->post($api_url, $data);
If you would like to send data using the application/x-www-form-urlencoded content type, you should call the asForm method before making your request.

Related

guzzle getbody function accessing the diffrenet elements of response

i am using guzzle to post some data to some api and recive some data back here is my code :
$response = $client->request('POST', 'http://url/api/v1/transaction/Verify', [
'headers' => ['Content-Type' => 'application/json'],
'body' => '{
"tn":"1905463527",
}'
]);
$responebody = $response->getBody();
i exacly dont know if i am getting string or object when ever i use getbody of guzzle but here is what i get when i echo the response :
{"errorCode":null,"errorMessage":"Canceled by user.","succeed":false,"tn":1905463527,"verifyCount":35,"amount":10000}
now here for example i want to access the "succeed " element and i want to know how can i access to check if it is true or not ,
You should check the Content-Type header and if it's application/json you can run json_decode on the body. Take this as an example
if ($response->getContentType() == 'application/json') {
$responseBody = json_decode($response->getContent());
// now you can access $responseBody->succeed
...
}

Using Config for api token gives error 'URI must be a string or UriInterface' Laravel

I am trying to make an API call.
If I do this: $url = "url-code.com?param1=value1&param2=value2&_token=enter-key-here";
I don't get any error.
If I do this: $url = "url-code.com?param1=value1&param2=value2&_token="+Config::get('app.john_doe_key');
I get an error: 'URI must be a string or UriInterface'
mycode
$statusCode = 200;
$url = "url-code.com?param1=value1&param2=value2&_token="+Config::get('app.john_doe_key');
$client = new Client();
$res = $client->get($url);
//dd($res);
return $res->getBody();
.env
JOHN_DOE_APP_KEY=key
config/app.php
'john_doe_key' => env('JOHN_DOE_APP_KEY'),
All right, based on our discussion in the comments of original question, here's what I would try.
Since everything in it's own works correctly, I would put all of the parameters in their own array:
$parameters = [
'someParam' => 'value',
'someOtherParam' => 'value',
'_token' => Config::get('app.john_doe_key')
];
And use http_build_query() to correctly format them:
$formattedParameters = http_build_query($parameters);
And finally, build the URL with what I have:
$url = "http://url-code.com?{$formattedParameters}";
You should be having a correctly formatted URL to use with Guzzle at this point.

Specify raw body of a POST request with Guzzle

With Guzzle (version 3), I'd like to specify the body of a POST request in "raw" mode. I'm currently trying this:
$guzzleRequest = $client->createRequest(
'POST',
$uri,
null,
'un=one&deux=two'
);
But it kind of doesn't work. If I dump my $guzzleRequest I can see that postFields->data is empty. Using $guzzleRequest->setBody() afterwards doesn't help.
However if I specify the body as ['un'=>'one', 'deux'=>'two'], it works as expected.
How can I specify the body of the request as 'un=one&deux=two'?
First I would highly recommend that you upgrade to Guzzle 6 as Guzzle 3 is deprecated and EOL.
It has been a long time since I used Guzzle 3 but I do believe you want the following:
$request = $client->post(
$uri,
$header = [],
$params = [
'un' => 'one',
'deux' => 'two',
]);
$response = $request->send();
Guzzle will automatically set the Content-Type header.
More information is available with the Post Request Documentation.
In response to your comment:
$request = $client->post(
$uri,
$headers = ['Content-Type' => 'application/x-www-form-urlencoded'],
EntityBody::fromString($urlencodedstring)
)
For this, reference: EntityBody Source and RequestFactory::create()

Laravel - POST data is null when using external request

I'm new to laravel, and I'm trying to implement a simple rest api.
I have the controller implemented, and tested via unit testing.
My problem is with the POST request.
Via the tests Input:json has data, via an external rest client it returns null.
This is the code on the unit test
$newMenu = array(
'name'=>'Christmas Menu',
'description'=>'Christmas Menu',
'img_url'=>'http://www.example.com',
'type_id'=>1,
);
Request::setMethod('POST');
Input::$json = $newMenu;
$response = Controller::call('menu#index');
What am I doing wrong?
UPDATE:
This is realy driving me crazy
I've instanciated a new laravel project and just have this code:
Routes
Route::get('test', 'home#index');
Route::post('test', 'home#index');
Controller:
class Home_Controller extends Base_Controller {
public $restful = true;
public function get_index()
{
return Response::json(['test'=>'hello world']);
}
public function post_index()
{
return Response::json(['test'=>Input::all()]);
}
}
CURL call:
curl -H "Accept:application/json" -H"Content-type: application/json" -X POST -d '{"title":"world"}' http://localhost/laravel-post/public/test
response:
{"test":[]}
Can anyone point me to what is wrong.
This is really preventing me to use laravel, and I really liked the concept.
Because you are posting JSON as your HTTP body you don't get it with Input::all();
You should use:
$postInput = file_get_contents('php://input');
$data = json_decode($postInput, true);
$response = array('test' => $data);
return Response::json($response);
Also you can use
Route::any('test', 'home#index');
instead of
Route::get('test', 'home#index');
Route::post('test', 'home#index');
Remove header Content-type: application/json if you are sending it as key value pairs and not a json
If you use : Route::post('test', 'XYZController#test');
Send data format : Content-type : application/json
For example : {"data":"foo bar"}
And you can get the post (any others:get, put...etc) data with :
Input::get('data');
This is clearly written in here : http://laravel.com/docs/requests
. Correct Content-type is very important!
I am not sure your CURL call is correct. Maybe this can be helpful : How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?
I am using Input::get('data') and it works.
I was facing this problem, my response of post was always null. To solve that I put the body key in guzzle object, like this
$client = new Client([
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => config('app.callisto_token'),
]
]);
$body = [
'firstResult'=> 0,
'data' => '05/05/2022'
];
$response = $client->post('http://'.$this->ip.'/IntegracaoERP'.'/status_pedido',
['body' => json_encode($body)]
);
Don't forget the json_encode in body key.
Hope this helps.

How to send data via using POST in Zend_Rest_Client

There is the next code:
$client = new Zend_Rest_Client('http://test.com/rest');
$client->sendData('data');
if i send via GET (echo $client->get()) it works correct
if via POST (echo $client->post()) i'm getting the next message "No Method Specified."
how to send post using Zend_Rest_Client?
Maybe this helps:
$base_url = 'http://www.example.com';
$endpoint = '/path/to/endpoint';
$data = array(
'param1' => 'value1',
'param2' => 'value2',
'param3' => 'value3'
);
$client = new Zend_Rest_Client($base_url);
$response = $client->restPost($endpoint, $data);
print_r($response);
Below is the link for the Zend_Rest_Client Class as it indicates we can use the public method restPost() to perform the post operation.
restPost ($path, $data=null)
Performs an HTTP POST request to $path.
http://www.sourcecodebrowser.com/zend-framework/1.10.3/class_zend_rest_client.html

Categories