php - 如何在PHP中使用curl GET发送原始数据?

标签 php curl php-curl

我正在开发 REST API,虽然很容易在 cURL 中为 POST 请求设置原始 JSON 数据

$payload = json_encode(array("user" => $data));

//attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

我不知道如何使用 GET 请求发送此类数据。

有类似CURLOPT_GETFIELDSCURLOPT_RAWDATA之类的东西吗?通过GET请求发送JSON的目的是为了传入一些参数。

我不想将表单数据添加到请求中,我希望发布 JSON,以便可以在接收器上解析它。

谢谢!

编辑:

基于评论,我想避免混淆,因此生成的请求应如下所示:

GET / HTTP/1.1
Host: 127.0.0.1:3000
Content-Type: application/json
Accept: application/json
Host: 127.0.0.1:3000
content-length: 13
Connection: keep-alive
cache-control: no-cache

{
    "a": "b"
}

如您所见,这里的 GET 请求包含数据,并且由 Web 服务器解析并完美运行。如何使用 cURL 实现此目的?

最佳答案

GET 请求没有主体,这就是整个想法:您只是从服务器获取一些内容,而不是向服务器发布一些内容。来自 RFC 7231 :

A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.

换句话说,GET 请求可以包含数据,但不应该包含数据。来自 earlier in the spec ,其中 GET 被定义为安全方法:

Request methods are considered "safe" if their defined semantics are essentially read-only; i.e., the client does not request, and does not expect, any state change on the origin server as a result of applying a safe method to a target resource.

...

Of the request methods defined by this specification, the GET, HEAD, OPTIONS, and TRACE methods are defined to be safe.

如果您确实希望在 GET 请求中包含 JSON(并将其发送到合理实现的服务器资源),那么它唯一可以去的地方就是在 URI 中作为查询字符串的一部分。对于 GET 请求,我发现使用 file_get_contents 比处理 cURL 容易得多。

<?php
$payload = json_encode(["user" => $data]);
$url_data = http_build_query([
    "json" => $payload
]);
$url = "https://some.example/endpoint.php?" . $url_data;

$result = file_get_contents($url);

如果你想将其发送到不合理实现的服务器资源,并且违反了 HTTP RFC 的精神,你可以这样做:

<?php
$url = "https://some.example/endpoint.php";
$payload = json_encode(["user" => $data]);
$ctx = stream_context_create(["http" => [
    "header"=>"Content-Type: application/json",
    "content"=>$payload
]]);
$result = file_get_contents($url, false, $ctx);

如果您决定专门使用 cURL 来执行此操作,那么您可能会幸运地使用 CURLOPT_CUSTOMREQUEST选项设置为“GET”和 CURLOPT_POSTDATA与您的数据。

关于php - 如何在PHP中使用curl GET发送原始数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56739950/

相关文章:

php - 使用.htaccess阻止通过/public/目录访问Laravel

php - PHP PDO 中的按钮

php - 在 DoExpressCheckout 上单击“购买”后,将日期时间保存到数据库时出错

php - 通过 CURL 设置 cookie (php)

c - 如何使用 libcurl 检查接收到的摘要信息

javascript - 通过 AJAX 将动态参数从 JavaScript 传递到 PHP 以在 cURL 调用中使用

php - 当我在 CURLOPT_HTTPHEADER 中添加 PayPal-Mock-Response 时出现 404 curl_error

php - Laravel 验证一个应该正好是 10 位数字的数字

curl - 谷歌分析测量协议(protocol)超时

scripting - 是否有 curl/wget 选项可以防止在出现 http 错误时保存文件?