无法使用PHP进行CURL发布请求

时间:2016-06-23 07:34:31

标签: php arrays curl

我读了一些Q& As但仍然在努力解决这个问题。我需要将一个特定的数组发布到API并获得另一个数组作为答案。

更新

我用过:

<?php

echo 'Testing cURL<br>';

// Get cURL resource
   $curl = curl_init();
   $data=array(array("UserId"=>"xxxx-10100","Password"=>"pass"));
   $sendpostdata = json_encode( array( "postdata"=> $data ) );
   echo $sendpostdata;
// Set some options - we are passing in a useragent too here
  curl_setopt_array($curl, array(
  CURLOPT_RETURNTRANSFER => 1,
  CURLOPT_URL => 'https://cloud.servicebridge.com/api/v1/Login',
  CURLOPT_HTTPHEADER => array('Accept: application/json','Content-Type: application/json'),
  CURLOPT_USERAGENT => 'Codular Sample cURL Request',
  CURLOPT_POST => 1,
  CURLOPT_POSTFIELDS => $sendpostdata
));
// Send the request & save response to $resp
  $resp = curl_exec($curl);
  echo $resp;
// Close request to clear up some resources
  curl_close($curl);

?>

这导致

Testing cURL {"postdata":[{"UserId":"xxxxx-10100","Password":"pass"}]} { "Data": null, "Success": false, "Error": { "Message": "Invalid UserId: ", "Value": "InvalidUserId", "Code": 9001 } }

没有控制台日志,没有其他消息或线索 我正在尝试实施此API https://cloud.servicebridge.com/developer/index#/  到了Worpdress。

API需要

{ "UserId": "string", "Password": "string" }

你能救我吗?我做错了什么

真的很感激,

Giannis

2 个答案:

答案 0 :(得分:2)

我已检查过给定的API并且REQUEST Parameters to access them,我认为您的初始数据(username and password)无法正确显示。请使用此代码: -

<?php
error_reporting(E_ALL); // check all type of errors
ini_set('display_errors',1); // display those errors
// Get cURL resource
$curl = curl_init();
$sendpostdata = json_encode(array("UserId"=>"xxxx-10100","Password"=>"pass"));
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
  CURLOPT_RETURNTRANSFER => 1,
  CURLOPT_URL => 'https://cloud.servicebridge.com/api/v1/Login',
  CURLOPT_HTTPHEADER => array('Accept: application/json','Content-Type: application/json'),
  CURLOPT_USERAGENT => 'Codular Sample cURL Request',
  CURLOPT_POST => 1,
  CURLOPT_POSTFIELDS => $sendpostdata
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
echo $resp;
// Close request to clear up some resources
curl_close($curl);
?>

注意: - 更改UserId&amp; Password值为您的真实值。谢谢

答案 1 :(得分:0)

这可能会帮助您生成正确的json。希望这会奏效。

使用此

   $data=array(array("UserId"=>"xxxxx-10100","Password"=>"pass"));

而不是

   $data ='[{"UserId":"xxxxx-10100","Password": "pass"}]';