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 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看