I have created a test function in my REST API (using the SLIM framework) for testing my implementation of a wrapper class for the cloudconvert API.
$app->get('/test', 'authenticate', function() use ($app) {
$response = array();
$converter = new CloudConverter();
$url = $converter->createProcess("docx","pdf");
$response["url"] = $url;
echoRespnse(201, $response);
});
My createProcess function inside CloudConverter class looks like this:
public function createProcess($input_format,$output_format)
{
$this->log->LogInfo("CreateProcess Called");
$headers = array('Content-type: application/json');
$curl_post_data = array('apikey' => API_KEY,'inputformat' => $input_format,'outputformat' => $output_format);
$curl = curl_init(CLOUD_CONVERT_HTTP);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($curl_post_data));
$curl_response = curl_exec($curl);
if ($curl_response === false)
{
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
$this->log->LogInfo('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response,true);
return $decoded['url'];
}
I have tested my API using Chrome Advanced Rest Client and i see a successful response from my call to the cloudconvert API but that is not what i was expecting as can be seen in the code above. I was expecting to extract the url and return THAT in my response.
My Questions is:
HOW can i extract the url from the response from cloudconvert and return that in my own response.
You need to use
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true)
to return response as a string: curl docs.
Related
I'm sending a requests via cURL to an external webservice and I'm receiving a response in JSON format. Something like this:
public function store(Request $request)
{
$loggedInUser = app('Dingo\Api\Auth\Auth')->user();
if (!$loggedInUser instanceof User) {
$this->response->errorUnauthorized();
}
$data = $request->all();
$url = env('WEBSERVICE_URL');
$payload = json_encode(['n' => $data['n']]);
$auth = 'Authorization: ' . env('API_KEY');
$headers = [
'Content-Type:application/json',
$auth
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
The problem is that the response of function is like this
{
"code": 200,
"status": "success",
"data": "{\"message\":\"n saved successfully!\"}"
}
And not like this (the json I received from the webservice)
{"message": "n saved successfully!"}
I'm not really an expert with Dingo API but I can imagine that this probably has to do with some kind of default response format Dingo applies to the returned values in the functions.
Anyways, in this case I would like it to return the second response above mentioned. Is there any way to disable the default response format Dingo applies in particular cases? Or do you think this is caused by something else?
I am unable to make the API call using CURL. Below is the code for making the API call using CURL
$ch=curl_init("http://sms.geekapplications.com/api/balance.php?authkey=2011AQTvWQjrcB56d9b03d&type=4");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array("Authorization: Bearer"));
// execute the api call
$result = curl_exec($ch);
echo ($result);
First you might wanna be using a function for this.. and your CURL it not build correctly. Please see my example
//gets geekapplications SMS balance
function getBalance() {
$url = 'http://sms.geekapplications.com/api/balance.php?' . http_build_query([
'authkey' => '2011AQTvWQjrcB56d9b03d',
'type' => '4'
]);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http == 200) {
$json = #json_decode($response, TRUE);
return $json;
} else {
echo 'There was a problem fetching your balance...';
}
}
Use it within your controller try print_r($this->getBalance()); should output an array with your balance.
I am trying to get the latest commit from github using the api, but I encounter some errors and not sure what the problem is with the curl requests. The CURLINFO_HTTP_CODE gives me 000.
What does it mean if I got 000 and why is it not getting the contents of the url?
function get_json($url){
$base = "https://api.github.com";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $base . $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($curl, CONNECTTIMEOUT, 1);
$content = curl_exec($curl);
echo $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return $content;
}
echo get_json("users/$user/repos");
function get_latest_repo($user) {
// Get the json from github for the repos
$json = json_decode(get_json("users/$user/repos"),true);
print_r($json);
// Sort the array returend by pushed_at time
function compare_pushed_at($b, $a){
return strnatcmp($a['pushed_at'], $b['pushed_at']);
}
usort($json, 'compare_pushed_at');
//Now just get the latest repo
$json = $json[0];
return $json;
}
function get_commits($repo, $user){
// Get the name of the repo that we'll use in the request url
$repoName = $repo["name"];
return json_decode(get_json("repos/$user/$repoName/commits"),true);
}
I use your code and it will work if you add an user agent on curl
curl_setopt($ch, CURLOPT_USERAGENT,'YOUR_INVENTED_APP_NAME');
I am using the HttpRequest class in my php script, but when I uploaded this script to my hosting provider's server, I get a fatal error when executing it:
Fatal error: Class 'HttpRequest' not found in ... on line 87
I believe the reason is because my hosting provider's php.ini configuration doesnt include the extension that supports HttpRequest. When i contacted them they said that we cannot install the following extentions on shared hosting.
So i want the alternative for httpRequest which i make like this:
$url= http://ip:8080/folder/SuspendSubscriber?subscriberId=5
$data_string="";
$request = new HTTPRequest($url, HTTP_METH_POST);
$request->setRawPostData($data_string);
$request->send();
$response = $request->getResponseBody();
$response= json_decode($response, true);
return $response;
Or How can i use this request in curl as it is not working for empty datastring?
You can use CURL in php like this:
$ch = curl_init( $url );
$data_string = " ";
curl_setopt( $ch, CURLOPT_POSTFIELDS, $data_string );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
curl_close($ch);
return $result;
and empty data string doesn't make sense in post request, but i've checked it with empty data string and it works quiet well.
you can use a framework like zend do this. framework usually have multiple adapters (curl,socket,proxy).
here is a sample with ZF2:
$request = new \Zend\Http\Request();
$request->setUri('[url]');
$request->setMethod(\Zend\Http\Request::METHOD_POST);
$request->getPost()->set('key', $value);
$client = new \Zend\Http\Client();
$client->setEncType('application/x-www-form-urlencoded');
$response = false;
try {
/* #var $response \Zend\Http\Response */
$response = $client->dispatch($request);
} catch (Exception $e) {
//handle error
}
if ($response && $response->isSuccess()) {
$result = $response->getBody();
} else {
$error = $response->getBody();
}
you don't have to use the entire framework just include (or autoload) the classes that you need.
Use the cURL in php
<?php
// A very simple PHP example that sends a HTTP POST to a remote site
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://example.com/feed.rss");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,"postvar1=value1&postvar2=value2");
// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// further processing ....
if ($server_output == "OK") { ... } else { ... }
?>
for more see this PHP Difference between Curl and HttpRequest
a slight variaton on the curl methods proposed, i decode the json that is returned, like in this snippet
I want to POST using HTTP_Request2 Pear Class. I was succefull when I used cURL to do the same, but I dont get response data when I use HTTP_Request. It says content length as 0. I read the PEAR documentation for HTTP_Request2 and followed it to write the code. It will be of great help if someone points out my errors. cURL method works but HTTP_Request2 method dosent. What I think is that the HTTP_Request2 method is unable to post the data, but I am not sure about the header too. My code is
function header()
{
$this->setGuid(guid());
$this->header = array($this->service,
time(), $this->getGuid());
return $this->header;
}
function header1()
{
$this->setGuid(guid());
$this->header = array('X-OpenSRF-service: '.$this->service,
'X-OpenSRF-xid: '.time(), 'X-OpenSRF-thread: '.$this->getGuid());
return $this->header;
}
function toArray()
{
$url4 = urldata($this->method, $this->param);
return $url4; //returns an encoded url
}
function send1()
{
require_once 'HTTP/Request2.php';
//------cURL Method-------------------------
$endpoint = $this->endpoint;
$data = $this->toArray();
$header = $this->header1();
$url_post = 'http://'.$endpoint.'/osrf-http-translator';
$this->curl = curl_init();
curl_setopt($this->curl, CURLOPT_URL, $url_post);
curl_setopt($this->curl, CURLOPT_HEADER, 1);
curl_setopt($this->curl, CURLOPT_POST, 1);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header);
$this->server_result = curl_exec($this->curl);
if (curl_error($this->curl) != 0 ) {
$error = 'Curl error: ' . curl_error($this->curl);
return $error;
}
var_dump ($this->server_result);
echo "<HR />";
//-----HTTP_REQUEST2 Method---------------
$request = new HTTP_Request2();
$request->setUrl($url_post);
$request->setHeader(array('X-OpenSRF-service' => $header[0], 'X-OpenSRF-xid' => $header[1], 'X-OpenSRF-thread' => $header[2]));
$request->setMethod(HTTP_Request2::METHOD_POST);
$request->addPostParameter($data);
var_dump ($request); echo "<HR />";
$response = $request->send(); var_dump($response);
}
The result of the HTTP_Request2::send() method is a little different to curl_exec. It is not as string, but another type, namely HTTP_Request2_Response.
To retrieve the response body as a string (a HTTP response contains the headers and a body), use the HTTP_Request2_Response::getBody method:
...
$response = $request->send();
$responseBody = $response->getBody();
This should do what you're looking for, $responseBody then is a string. In more general terms: HTTP_Request2 has an object-oriented interface. This allows to use different adapters (e.g. Curl as well as sockets or you can even write your own one, e.g. for testing) as well as retrieving the response body in a streaming fashion (e.g. with large responses you do not put all into a single string at once).