代码之家  ›  专栏  ›  技术社区  ›  Kevin.a

在curl不工作的情况下发布到api

  •  0
  • Kevin.a  · 技术社区  · 8 年前
    $headers = array();
    $headers[] = 'Authorization: hmac ' .$websiteKey.':'.$hmac .':'.$nonce . ':'.$time;
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($curl,CURLOPT_POSTFIELDS, $post);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);    
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($curl);
    
    var_dump($result);
    
    
    curl_close($curl);
    

    我有上面的代码,我想发布到一个API。不知怎么的,它不起作用。我尝试对结果变量使用var_转储。结果是:

    string(117) "{"Message":"The request entity's media type 'application/x-www-form-urlencoded' is not supported for this resource."}"
    

    知道为什么不发布到API吗?

    $post的值=

    {"AmountDebit":10,"Currency":"EUR","Invoice":"testinvoice 123","Services":{"ServiceList":[{"Action":"Pay","Name":"ideal","Parameters":[{"Name":"issuer","Value":"ABNANL2A"}]}]}}
    

    标题:

    $headers[] = 'Authorization: hmac ' .$websiteKey.':'.$hmac .':'.$nonce . ':'.$time;
    
    2 回复  |  直到 8 年前
        1
  •  2
  •   iainn    8 年前

    如果不指定 Content-Type 头当使用curl进行后期调用时,它将在值中添加一个 application/x-www-form-urlencoded .

    来自 Everything Curl book :

    使用curl的-d选项发布将使其包含一个看起来像内容类型的默认头段:application/x-www-form-urlencoded。这就是典型的浏览器将用于普通邮件的功能。

    许多post数据的接收者不关心或检查content-type头。

    如果这个标题对您来说不够好,那么您当然应该替换它并提供正确的标题。

    根据您的请求,我想您需要在脚本顶部添加以下内容:

    $headers[] = 'Content-Type: application/json';
    

    但根据您要发布到的确切API,这可能需要有所不同。

        2
  •  -1
  •   Shailesh    8 年前

    你在使用前安装过curl吗? 如果没有安装,请尝试Google进行curl安装 并使用我的curl函数进行post请求,它100%工作。-

    public function curlPostJson() {
        $headers = [];
        $headers[] = 'Content-Type: application/json';
        $headers[] = 'Content-Length: ' .strlen(json_encode($paramdata));
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($paramdata));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
        $server_output = curl_exec($ch);
        curl_close($ch);
        return json_decode($server_output);
    }
    
    推荐文章