我正在尝试将JSON发送到java Web服务,但是从web服务获得响应所有null的响应,请参阅下文。我的代码有什么问题吗?
$buildApplication = array(
'firsname' => 'Keith',
'surname' => 'Francis',
'companyName' => 'Keiths Mobile Discos',
'phone' => '07123456789',
'email' => 'keith.francis@freedom-finance.co.uk',
'sourceCode' => 'W00T'
);
$data = json_encode($buildApplication);
$ch = curl_init('http://10.50.1.71:8080/SME/api/details.json');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data))
);
$result = curl_exec($ch);
var_dump($result);
回复
string(1042) "{"errors":[{"object":"com.application.AppDetails","field":"firstname","rejected-value":null,"message":"Property [firstname] of class [class com.application.AppDetails] cannot be null"},{"object":"com.application.AppDetails","field":"surname","rejected-value":null,"message":"Property [surname] of class [class com.application.AppDetails] cannot be null"},{"object":"com.application.AppDetails","field":"companyName","rejected-value":null,"message":"Property [companyName] of class [class com.application.AppDetails] cannot be null"},{"object":"com.application.AppDetails","field":"phone","rejected-value":null,"message":"Property [phone] of class [class com.application.AppDetails] cannot be null"},{"object":"com.application.AppDetails","field":"email","rejected-value":null,"message":"Property [email] of class [class com.application.AppDetails] cannot be null"},{"object":"com.application.AppDetails","field":"sourceCode","rejected-value":null,"message":"Property [sourceCode] of class [class com.application.AppDetails] cannot be null"}]}"
答案 0 :(得分:0)
firsname
而非firstname
。 json_encode
两次。尝试如下:
$buildApplication = array(
'firstname' => 'Keith',
'surname' => 'Francis',
'companyName' => 'Keiths Mobile Discos',
'phone' => '07123456789',
'email' => 'keith.francis@freedom-finance.co.uk',
'sourceCode' => 'W00T'
);
$data = json_encode($buildApplication);
$ch = curl_init('http://10.50.1.71:8080/SME/api/details.json');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data))
);
$result = curl_exec($ch);
var_dump($result);
答案 1 :(得分:0)
您已经使用了两次json_encode。
将以下行写为: -
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);