Kevin.a
Kevin.a

Reputation: 4306

Posting to API with curl not working

$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);

I have the code above, i want to post to an api. Somehow its not working. I tried using a var_dump on the result variable. The result is:

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

Any idea why its not posting to the api?

The value of the $post=

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

Headers:

$headers[] = 'Authorization: hmac ' .$websiteKey.':'.$hmac .':'.$nonce . ':'.$time;

Upvotes: 0

Views: 1499

Answers (2)

Shailesh Kumar
Shailesh Kumar

Reputation: 47

Have You installed curl before using it. If it not install try google for Curl installation and use my curl function for post request its 100% working-

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

Upvotes: -2

iainn
iainn

Reputation: 17433

If you don't specify a Content-Type header when making a POST call with Curl, it will add one in with the value application/x-www-form-urlencoded.

From the Everything Curl book:

POSTing with curl's -d option will make it include a default header that looks like Content-Type: application/x-www-form-urlencoded. That's what your typical browser will use for a plain POST.

Many receivers of POST data don't care about or check the Content-Type header.

If that header is not good enough for you, you should, of course, replace that and instead provide the correct one.

Judging by your request, I imagine you'll need to add the following to the top of your script:

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

But depending on the exact API you're posting to, this might need to be different.

Upvotes: 2

Related Questions