gpt4 book ai didi

php - 在 PHP 中向 REST API 发送 JSON POST 请求

转载 作者:行者123 更新时间:2023-12-03 18:41:22 25 4
gpt4 key购买 nike

我需要使用 JSON 对象作为主体发出 POST 请求。这两种方法都给我 HTTP 500 服务器错误。我的代码有什么明显的错误吗?要温柔...我尝试了几种方法,包括

$checkfor = ("'serverId':'Server','featureId':'Feature','propertyId':'Property'");
$checkforJson = json_encode($checkfor);
$uri = "http://localhost:8080/v1/properties";
$response = \Httpful\Request::post($uri)
->method(Request::post)
->withoutStrictSsl()
->expectsJson()
->body($checkforJson)
->send();
pre($response);

使用 HTTPful 资源。我尝试过使用 cURL

$service_url = "http://localhost:8080/v1/properties";

// Initialize the cURL
$ch = curl_init($service_url);

// Set service authentication

// Composing the HTTP headers
$body = array();
$body[] = '"serverId" : "Server"';
$body[] = '"featureId" : "Feature"';
$body[] = '"propertyId" : "Property"';
$body = json_encode($body);

$headers = array();
$headers[] = 'Accept: application/xml';
$headers[] = 'Content-Type: application/xml; charset=UTF-8';

// Set the cURL options
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

curl_setopt($ch, CURLOPT_TIMEOUT, 15);

// Execute the cURL
$data = curl_exec($ch);

// Print the result
pre($data);

最佳答案

不久前我也遇到过类似的问题。

对我有用的解决方案是:

$url = 'http://yourURL.com/api';
$data = array('field1' => 'value', 'field2' => 'value');
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n",
'method' => 'POST',
'content' => json_encode($data),
)
);

$context = stream_context_create($options);
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );

可以找到类似的答案 HERE

关于php - 在 PHP 中向 REST API 发送 JSON POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52988021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com