【发布时间】:2016-11-15 22:00:35
【问题描述】:
我需要将一些 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.
?>
我收到以下异常“内容类型必须是:应用程序/json”。为什么?我已将内容类型设置为 application/json。正确的?请帮助立即。
【问题讨论】:
-
什么是响应内容类型?
$contentType的值? -
$contentType 是 application/x-www-form-urlencoded
-
而不是从 php 输入中读取。您可以尝试从
$_POST获取。curl_setopt($ch, CURLOPT_POSTFIELDS,array('json'=>$json));你可以在$_POST['json']得到结果