如何使用PHP中的post方法使用标头发送带有标头的JSON数据(cURL)

时间:2018-02-02 12:06:06

标签: php json laravel curl

我尝试在post方法中使用json数据和标头常量类型发送请求下面的代码:application / json

$ch_get = curl_init($url_get);
        $jsonData1_get_r = array(
            'customerMobileNo'=>'9040845440',
            'recipientMobileNo'=>'7008565316',
            'recipientName'=>'Name Test Test',
            'accountNo'=>'5928374737328009',
            'bankName'=>'HDFC',
            'accIfsc'=>'HDFC0002058',
            'transactionType'=>'IMPS',
            'amount'=>'100'
            );
        $jsonDataEncoded_get = json_encode($jsonData1_get_r);

        curl_setopt($ch_get, CURLOPT_POST, 1);
        curl_setopt($ch_get, CURLOPT_POSTFIELDS, $jsonDataEncoded_get);
        curl_setopt($ch_get, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch_get, CURLOPT_HTTPHEADER, array('Authorization: '.$token.''));
        curl_setopt($ch_get, CURLOPT_RETURNTRANSFER, TRUE);
        $result_get = curl_exec($ch_get);
        curl_close($ch_get);

当使用上面的代码时出现错误

内容类型' application / x-www-form-urlencoded; charset = UTF-8'不支持

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码来实现目标

$jsonData1_get_r = array(
        'customerMobileNo'=>'9040845440',
        'recipientMobileNo'=>'7008565316',
        'recipientName'=>'Name Test Test',
        'accountNo'=>'5928374737328009',
        'bankName'=>'HDFC',
        'accIfsc'=>'HDFC0002058',
        'transactionType'=>'IMPS',
        'amount'=>'100'
        ); 

$jsonDataEncoded_get  = json_encode($jsonData1_get_r );
$ch_get = curl_init($url_get);
curl_setopt($ch_get, CURLOPT_CUSTOMREQUEST, "POST"); 
curl_setopt($ch_get, CURLOPT_POSTFIELDS, $jsonDataEncoded_get );
curl_setopt($ch_get, CURLOPT_RETURNTRANSFER, true);    
curl_setopt($ch_get, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Authorization: ' . $token)                                                                       

);      

希望你能帮助你!!

谢谢&此致