正确地发布到此API

时间:2017-07-20 03:26:16

标签: php api curl post

我正在尝试发布到API。不幸的是,我无法通过身份验证。

$apiKey = 'mykey';
$username = 'myuid';
$userKey = 'myuserkey';
$url = 'https://api.thetvdb.com/login?';
$LoginQuery = array('apikey' => $apiKey,
                    'userkey' => $userKey,
                    'username' => $username
                    );
$postfields = json_encode($LoginQuery);
$urlquery = $url . json_encode($LoginQuery);
p_print("URL: " . $urlquery);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close($ch);
print_r($json);

响应:

{
  "Error": "Bad Content-Type or charset, expected 'application/json'"
}

不是我发布的json?我怎么做错了?

1 个答案:

答案 0 :(得分:4)

您需要将Content-Type设置为application/json

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));