将curl转换为PHP

问题描述:

我尝试在curl下面使用终端工作正常,它返回一个字符串Ok或失败。将curl转换为PHP

curl -k -X POST -H 'Content-Type: application/json' -d '{"username":"username","password":"password"}' https://123.123.123.123:1234/session 

当我尝试转换为它不工作。

<?php 
$data = array("username" => "username", "password" => "password"); 

$data_string = json_encode($data); 

$ch = curl_init("https://123.123.123.123:1234/apicall"); curl_setopt_array($ch, array(CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_HTTPHEADER => array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string))), CURLOPT_POSTFIELDS => $data_string, CURLOPT_RETURNTRANSFER => true)); 

$result = curl_exec($ch); //Make it all happen and store response 

?> 

curlopt_postfields接受一个数组,所以你不需要json_encode数据数组:

CURLOPT_POSTFIELDS => $data 

查看curlopt选项的详细信息:

此参数可以被传递作为urlencoded字符串,如 'para1 = val1 & para2 = val2 & ...'或作为字段na的数组我作为键 和字段数据作为值。

您的示例中还有一个太多的圆括号,并且您没有关闭连接。完整代码:

<?php 
$data = array("username" => "username", "password" => "password"); 

$ch = curl_init("https://123.123.123.123:1234/apicall"); 
curl_setopt_array(
    $ch, 
    array(
     CURLOPT_CUSTOMREQUEST => "POST", 
     CURLOPT_HTTPHEADER => array(
      'Content-Type: application/json', 
      'Content-Length: ' . strlen($data) 
     ), 
     CURLOPT_POSTFIELDS => $data_string, 
     CURLOPT_RETURNTRANSFER => true 
    ) 
); 

$result = curl_exec($ch); 

curl_close($ch); 
+0

应改变'Content-Length:'。 strlen($ data_string)和CURLOPT_POSTFIELDS => $ data_string –