【问题标题】:How send POST request with JSON in php?如何在 php 中使用 JSON 发送 POST 请求?
【发布时间】:2021-01-10 01:32:06
【问题描述】:

我尝试将请求从帖子类型发送到服务器,但没有成功,它返回状态为 400 的 BadRequest,

我的代码:

<?php

$products = array('1'=>array('amount'=>'1','product_id'=>'11250'));
$data = array('id' => '67', 'shipping' => '61', 'payment'=> '2','products'=> $products);
$cert = base64_encode('myapp@myapp.co.il:1234abcd');
$url = "https://myapp.co.il/api/aaa";


$ch = curl_init($url);
$payload = json_encode($data);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "authorization: Basic ".$cert,
    "Content-Type: application/json",
    "cache-control: no-cache"
    ));
$result = curl_exec($ch);
curl_close($ch);
var_dump($result);

?> 

它如此回报我:

array (2) {["message"] => string (51) "Bad Request: Syntax error, distorted JSON" ["status"] => int (400)}

【问题讨论】:

标签: php post https


【解决方案1】:

我看到你准备了变量$payload 发送,但发送$postdata 而不是curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata)

【讨论】:

  • 你说得对,我的错误,但我纠正了它,它没有帮助......
  • 进一步,您可能希望在 /api/aaa 导致的代码的接收部分中进行调试。检查这个答案stackoverflow.com/a/15643608/4984011
猜你喜欢
  • 1970-01-01
  • 2011-08-04
  • 2018-02-07
  • 2021-01-09
  • 2014-11-19
  • 2021-11-30
相关资源
最近更新 更多