【问题标题】:How to send JSON data in body with header using post method in PHP(cURL) [duplicate]如何使用 PHP(cURL)中的 post 方法在正文中发送带有标头的 JSON 数据 [重复]
【发布时间】:2018-07-12 22:24:51
【问题描述】:

我尝试使用以下代码在 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”

【问题讨论】:

  • 我不确定,但您是否尝试过在同一个数组中同时设置两个标题?从目前的使用方式来看,Content-Type 似乎被覆盖了。
  • 类似curl_setopt($ch_get, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: '.$token));

标签: php json laravel curl


【解决方案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)                                                                       

);      

希望对你有帮助!!

感谢和问候

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-13
    • 2016-01-31
    • 2016-03-27
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    相关资源
    最近更新 更多