我在PHP上运行了一个应用程序。现在,我有一个要求,我必须向在JAVA上运行的服务器(包括json数据)发送API请求(POST方法)。我试图使用php的curl方法,但无法发送请求。我尝试了以下代码。
$data = array("user_id"=>"6cdedfcc-ff55-449f-8362-af3ae0e04928");
$data_string = json_encode($data);
$ch = curl_init('https://java-api-url/api');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
print_r($result);
答案 0 :(得分:1)
也许你可以试试这个:
curl_setopt($ ch,CURLOPT_POST,1);
而不是:
curl_setopt($ ch,CURLOPT_CUSTOMREQUEST," POST");
答案 1 :(得分:0)
$data = NULL;
$data['user_id'] = "6cdedfcc-ff55-449f-8362-af3ae0e04928";
$data_string = json_encode($data);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'https://java-api-url/api');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
print_r($result);