duanlan8763 2016-05-24 14:09
浏览 248
已采纳

API HTTP / Request2.php到CURL

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;
}

?>
  • 写回答

1条回答 默认 最新

  • dsfb20227 2017-04-26 07:18
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示