Api 调用在 Postman 中工作正常,但在 PHP CURL 中不起作用

问题描述 投票:0回答:1

我有一个在邮递员中运行良好的 api。但我在 PHP CURL 中尝试了相同的 api,没有办法让它工作。 这是邮递员声明的屏幕截图: enter image description here

这里是PHP版本

 $data = array(
'prompt' => "write me a poem",
'use_buffer' => 1);
   

$api_url="https://myserver.com" ;

$ch = curl_init();

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($data) );

/*curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json'
));*/

$headers = array();
$headers[] = 'Accept: application/json';

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_VERBOSE, true);

//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . len($data)));
      
$response = curl_exec($ch);
       
curl_close($ch);
var_dump($response);
print("<br>");

感谢您的反馈

php curl
1个回答
0
投票

代码中的问题

  1. 缺少 Content-Type 标头:请求以 JSON 格式发送数据,但未在标头中指定。
  2. 潜在的服务器误解:如果没有 Content-Type 标头,服务器可能无法正确理解 JSON 数据。

PHP CURL POST 请求代码及更正

<?php

// Your data to be sent
$data = array(
    'prompt' => "write me a poem",
    'use_buffer' => 1
);

// The URL of the API
$api_url = "https://myserver.com";

// Initialize cURL session
$ch = curl_init();

// Disable SSL verification (not recommended for production)
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

// Set the data to be sent in the request body
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

// Specify the headers for the request
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Accept: application/json';

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_VERBOSE, true);

$response = curl_exec($ch);
curl_close($ch);

var_dump($response);
print("<br>");

?>
© www.soinside.com 2019 - 2024. All rights reserved.