首页 > 解决方案 > 请求带有标头的 Curl 请求

问题描述

我是 curl 的新手,我想使用以下结构发送带有标头的 curl 请求

$ curl -H 'X-API-Key: INSERT_YOUR_API_KEY_HERE'           \
       -F 'image_url=https://www.remove.bg/example.jpg'   \
       -F 'size=auto'                                     \
       -f https://api.remove.bg/v1.0/removebg -o no-bg.png 

这是我正在使用的代码

function cUrl($url, $post_fields = null, $headers = null) {
            $ch = curl_init();
            $timeout = 5;
            curl_setopt($ch, CURLOPT_URL, $url);
            if ($post_fields && !empty($post_fields)) {
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
            }
            if ($headers && !empty($headers)) {
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            }
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $data = curl_exec($ch);
            if (curl_errno($ch)) {
                echo 'Error:' . curl_error($ch);
            }
            curl_close($ch);
            return $data;
        }
$url = "https://api.remove.bg/v1.0/removebg";
    $post_fields = 'image_url=https://example.com/1.png&size=auto';
    $headers = array(
        'Content-Type' => 'application/x-www-form-urlencoded',
        'charset' => 'utf-8',
        'X-API-Key'=>'1234567890'
        );
    $data = $bg->cUrl($url, $post_fields, $headers);

这就是我得到的

{"errors":[{"title":"Missing API Key","code":"auth_failed","detail":"请通过 X-Api-Key 请求标头提供您的 API 密钥"}]}

我如何发送这个请求?

标签: phphttpphp-curl

解决方案


推荐阅读