我正在开发 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_GETFIELDS
或CURLOPT_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/