I am using GuzzleHttp to send request to external api and get response, but the response returned is empty from data. and when i test a uri and parameters in advanced rest client i get a data,So why Guzzle response is empty?!
please help me if you can.
here is my code:
public function index($id)
{
$client = new Client(['base_uri' => 'http://qpeople.me/']);
$response=$client->post('profileinfo', [
'json'=>[
'tshirtID'=>$id
]
]);
$body=$response->getBody();
dd($body);
return view('profile');
}
this is the response
Ok,I found the solution by using cURL to send the request and get a response,
here is the code:
$url = 'http://qpeople.me/profileinfo';
$data['tshirtID'] =$id;
$_data = json_encode($data);
$headers = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($_data),
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $_data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
try:
<?php
$body = (string) $response->getBody();
dd($body);
Related
I checked the API documentation but there are no examples related to curl php.
Can i get some guide on how to connect with monday.com to create lead or deal in monday.com using curl php?
I have sample code (Token is wrong in this code snippet), but I have no idea on how to pass data to create lead
<?php
$token = 'eyJhbGciOiJIUzI1NiJ9.0Y-0OesftWBt2SamhvuPV5MR-0Oq7iApMt2exFkDNdM';
$apiUrl = 'https://api.monday.com/v2';
$headers = ['Content-Type: application/json', 'Authorization: ' . $token];
$query = '{ boards (limit:1) {id name} }';
$data = #file_get_contents($apiUrl, false, stream_context_create([
'http' => [
'method' => 'POST',
'header' => $headers,
'content' => json_encode(['query' => $query]),
]
]));
$responseContent = json_decode($data, true);
echo json_encode($responseContent);
?>
I'm not familiar with this monday.com page, but this is how you can make a cURL request in PHP:
<?php
$token = 'eyJhbGciOiJIUzI1NiJ9.0Y-0OesftWBt2SamhvuPV5MR-0Oq7iApMt2exFkDNdM';
$apiUrl = 'https://api.monday.com/v2';
$headers = ['Content-Type: application/json', 'Authorization: ' . $token];
// Payload
$query = '{ boards (limit:1) {id name} }';
$payload = ['query' => $query];
// Init cURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_URL, $apiUrl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// Exec cURL
$resp = curl_exec($curl);
// Close cURL
curl_close($curl);
// Get response
$response = #json_decode($resp, true);
I'm trying to get data posted using cURL in my endpoint, which is built on Laravel. In my API controller, where I receive data, I am able to receive all the data except my media file. I check for presence of the file using $request->hasFile('file') but it returns false. I also try to get the file using $request->file('file') but it returns null.
When I use $request->get('file'), I get the following response.
file":{"name":"/Users/name/File/path/public/media/aaaah.wav","mime":null,"postname":null}
Below, I am using $headers[] = "Content-Type: application/json"; to convert the recipient from array to string. Can anyone help me understand why the file posted by cURL is not being received in my Laravel method when I use $request->hasFile('file') and $request->file('file')?
AppController
public function postCurlData()
{
$endPoint = 'http://127.0.0.1:9000/api';
$apiKey = '****';
$url = $endPoint . '?key=' . $apiKey;
$dir = '/Users/name/File/path/app/public/media/test.wav'; // full directory of the file
$curlFile = curl_file_create($dir);
$data = [
'recipient' => ['44909090', '44909090'],
'content' => 'i love to code',
'file' => $curlFile,
];
$ch = curl_init();
$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
$result = json_decode($result, TRUE);
curl_close($ch);
}
My endpoint where I'm receiving data:
APIController
public function receiveCurlData()
{
$apiKey = $request->get('key');
if (($apiKey)) {
return response()->json([
'status' => 'success',
'content' => $request->get('content'),
'recipient' => $request->get('recipient'),
'file' => $request->hasFile('file')
]);
}
}
Response
{"status":"success","content":"I love to code","recipient":
["44909090","44909090"],"file":false}
This answer is related to your question:
how to upload file using curl with php.
You should delete
$headers = array();
$headers[] = "Content-Type: application/json";
And
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
And also delete the json_encode() replacing it by the plain array
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
$result = json_decode($result, TRUE);
curl_close($ch);
I am trying to do a POST request to an endpoint with Zend2.
I can do the post in PHP using Curl, but cannot reproduce that Curl request using Zend2 Client and Request.
For example, the following works fine.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
$postfields = array();
$postfields['CostCode'] = '999999801';
curl_setopt($ch, CURLOPT_POSTFIELDS,
$postfields);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data;
charset=UTF-8',
'Connection: Keep-Alive'
));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
Result returned:-
<ValidateCCResult xmlns="http://ws.apache.org/ns/synapse">
<Result>1</Result></ValidateCCResult>
Indicating that the costcode is valid.
But, when I try and reproduce this in Zend, I don't get the response I expect.
$postfields = array();
$postfields['CostCode'] = '999999801';
$client = new \Zend\Http\Client();
$client->setAdapter(new \Zend\Http\Client\Adapter\Curl());
$request = new \Zend\Http\Request();
$request->setUri($url);
$request->setMethod(\Zend\Http\Request::METHOD_POST);
$request->getHeaders()->addHeaders([
'Content-Type' => 'multipart/form-data; charset=UTF-8'
]);
$request->setContent($postfields);
$response = $client->dispatch($request);
<ValidateCCResult xmlns="http://ws.apache.org/ns/synapse"><Result>0</Result>
<Message/></ValidateCCResult>
I have tried different content-types, but have a feeling it is something to do with setContent changing the array of $postfields.
Try to use
$postfields['CostCode'] = '999999801';
$uri = 'http://localhost';
$client = new \Zend\Http\Client();
$client->setUri($uri);
$client->setMethod('POST');
$client->setOptions(array(
'keepalive' => true,
));
$client->setEncType(\Zend\Http\Client::ENC_FORMDATA);
$client->setParameterPost($postfields);
$response = $client->send();
echo $response->getBody();
I am able to "GET" the activity stream but not "POST" to it. It seems its a technical error.
This is the code which works for getting the activity stream:
function getActivityStream()
{
$as=$this->request('https://www.yammer.com/api/v1/streams/activities.json');
var_dump($as);
}
function request($url, $data = array())
{
if (empty($this->oatoken)) $this->getAccessToken();
$headers = array();
$headers[] = "Authorization: Bearer " . $this->oatoken['token'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($data) );
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
return json_decode($output);
}
ok so that works fine...
the code below, returns a Yammer "oops this page could not be found" message:
function putActivityStream()
{
$data=array('type'=>'text', 'text'=>'hello from api test call');
$json=json_encode($data);
$res=$this->post('streams/activites.json',$json);
}
function post($resource, $data)
{
if (empty($this->oatoken)) $this->getAccessToken();
$ch = curl_init();
$headers = array();
$headers[] = "Authorization: Bearer " . $this->oatoken['token'];
$headers[]='Content-Type: application/json';
$url = 'https://www.yammer.com/api/v1/' . $resource;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
return $response;
}
One of the examples from:
http://developer.yammer.com/api/streams.html
POST https://www.yammer.com/api/v1/streams/activities.json
Requests must be content-type: application/json.
{
"type": "text",
"text": "The build is broken."
}
You're going to kick yourself. You have a typo in your code. :)
Change:
$res=$this->post('streams/activites.json',$json);
to
$res=$this->post('streams/activities.json',$json);
Simples.
I have an API that requires HTTP/Request2.php.
( Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
can I use CURL instead , is there is any way not to use this Component ?
here is the API code
<?php
require_once 'HTTP/Request2.php';
$request = new Http_Request2('http://ww');
$url = $request->getUrl();
$headers = array(
// Request headers
'Content-Type' => 'application/json',
'Ocp-Apim-Subscription-Key' => '{subscription key}',
);
$request->setHeader($headers);
$parameters = array(
// Request parameters
);
$url->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_POST);
// Request body
$request->setBody("{body}");
try
{
$response = $request->send();
echo $response->getBody();
}
catch (HttpException $ex)
{
echo $ex;
}
?>
Knowing this question was asked almost a year ago, I thought I should contribute an answer since I came up with the same problem and it may have happened to others as well.
Judging by the code given and the Ocp-Apic-Subscription-Key header, I guess you are trying to communicate with Microsoft's Vision API (Documentation). Here's what I used in order to communicate with the API via cURL:
$headers = array(
// application/json is also a valid content-type
// but in my case I had to set it to octet-steam
// for I am trying to send a binary image
'Content-Type: application/octet-stream',
'Ocp-Apim-Subscription-Key: {subscription key}'
);
$curl = $curl_init();
curl_setopt($curl, CURLOPT_FRESH_CONNECT, true); // don't cache curl request
curl_setopt($curl, CURLOPT_URL, '{api endpoint}');
curl_setopt($curl, CURLOPT_POST, true); // http POST request
// if content-type is set to application/json, the POSTFIELDS should be:
// json_encode(array('url' => $body))
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // return the transfer as a string of the return value
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
// disabling SSL checks may not be needed, in my case though I had to do it
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($curl);
$curlError = curl_error($curl);
curl_close($curl);