从api发送和接收json数据

时间:2016-07-13 10:50:29

标签: php json curl send

我需要将一些json数据发送到url并接收其json响应。我不是很擅长json,我搜索并找到以下代码

<?php
$json_data = array(
'partnerid' => '123',
'outletid' => '321',
'mobile' => '0123456789',
'secret' => 'qwert',
'amount' => '100',
);

$json = json_encode($json_data, true);

$req_url = "https://myapiprovider.com/api/requestdata";

//send json request
//Initiate cURL.
$ch = curl_init($req_url);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
//Execute the request
$result = curl_exec($ch);

//receive json response
$content = file_get_contents($req_url);
//Make sure that it is a POST request.
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
throw new Exception('Request method must be POST!');
}

//Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the incoming RAW post data from JSON.
$decoded = json_decode($content, true);
//If json_decode failed, the JSON is invalid.
if(!is_array($decoded)){
throw new Exception('Received content contained invalid JSON!');
}
//Process the JSON.
?>

我收到以下异常'内容类型必须是:application / json'。为什么?我已将内容类型设置为application / json。对?请帮助移民。

1 个答案:

答案 0 :(得分:1)

$json_data = array(
'partnerid' => '123',
'outletid' => '321',
'mobile' => '0123456789',
'secret' => 'qwert',
'amount' => '100',
);

$json = json_encode($json_data, true);
$req_url = "https://myapiprovider.com/api/requestdata";

$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $req_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, count($json));
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($curl,CURLOPT_POSTFIELDS, $json);
$result = curl_exec($curl);
curl_close($curl);
$result = json_decode($result);