我需要向网址发送json post请求。我正在使用php curl class
。但是,即使我已经设置了内容类型,我的请求标头也始终将内容类型显示为application/x-www-form-urlencoded
。这是我的代码
$curl1 = new Curl();
$curl1->setOpt(CURLOPT_RETURNTRANSFER, TRUE);
$curl1->setOpt(CURLOPT_HEADER, FALSE);
$curl1->setOpt(CURLOPT_POST, TRUE);
$curl1->setOpt(CURLOPT_POSTFIELDS, $data);
$curl1->setOpt(CURLOPT_HTTPHEADER, array(
"content-type:application/json"
));
$curl1->setBasicAuthentication('username', 'password');
$curl1->post('https://example.com/url');
我从api获得500 error
。我联系了他们,他们说你的内容类型不对。我打印出了类似
CaseInsensitiveArray Object
(
[container:Curl\CaseInsensitiveArray:private] => Array
(
[Request-Line] => POST /url HTTP/1.1
[Authorization] => Basic Yccx4MzA1ZTU0MDkwNDA3OGI1OWI4YjUyNjI4MjJjNTM6MTddfhf7755Y1ZDQ0NDVmY2I2NTEzZjllNTU3MzI4MTM=
[User-Agent] => PHP-Curl-Class/3.4.5 (+https://github.com/php-curl-class/php-curl-class) PHP/5.5.24 curl/7.36.0
[Host] => ssapi.shipstation.com
[Accept] => */*
[Content-Type] => application/x-www-form-urlencoded
)
)
请检查请求标头和我的代码中的内容类型。它们是不同的。我正在设置Content-Type: applicaiton/json
,为什么在请求中显示application/x-www-form-urlencoded
?
这是我发送的json
{"orderNumber":"BENORDER","orderDate":"2015-05-31T03:38:36-0700","orderStatus":"awaiting_shipment","billTo":{"name":"Stack Yu","company":null,"street1":" Stockton AVenue","city":"Plainfield","state":"IL","postalCode":"44444"},"shipTo":{"name":"Stack Yu","company":null,"street1":" Stockton AVenue","city":"Plainfield","state":"IL","postalCode":"44444"},"items":[{"sku":"S102","name":"My Prodcut","quantity":"1"}]}
非常感谢任何帮助!
答案 0 :(得分:1)
php-curl-class有一个单独的方法来设置标题,请检查the documentation。所以,你必须使用:
$curl1->setHeader("Content-Type", "application/json");
并设置Content-Type
标题。