Reputation: 33
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;
}
?>
Upvotes: 1
Views: 1397
Reputation: 309
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);
Upvotes: 3