PHP cURL GET请求和请求的正文 [英] PHP cURL GET request and request's body
问题描述
我正在尝试使用cURL作为GET请求,如下所示:
i'm trying using cURL for a GET request like this:
function connect($id_user){
$ch = curl_init();
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
);
curl_setopt($ch, CURLOPT_URL, $this->service_url.'user/'.$id_user);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
$body = '{}';
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$authToken = curl_exec($ch);
return $authToken;
}
因为你看到我想传递$ body作为请求的身体,我不知道它的正确与否,我不能调试这个实际上,你知道是否是正确的使用 curl_setopt($ ch,CURLOPT_POSTFIELDS,$ body);
有GET请求?
As you an see i want to pass $body as the request's body , but i don't know if its correct or not and i can't debug this actually, do you know if is the right to use curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
with a GET request?
因为这个enteire代码与POST完美配合,现在我尝试改变这个GET,你可以看到
Cause this enteire code works perfect with POST, now i'm trying change this to GET as you can see
推荐答案
CURLOPT_POSTFIELDS
顾名思义,用于 POST
请求。对于 GET
请求,有效内容是以查询字符串形式的URL的一部分。
CURLOPT_POSTFIELDS
as the name suggests, is for the body (payload) of a POST
request. For GET
requests, the payload is part of the URL in the form of a query string.
,您需要使用您需要发送的参数(如果有)构建URL,并删除cURL的其他选项。
In your case, you need to construct the URL with the arguments you need to send (if any), and remove the other options to cURL.
curl_setopt($ch, CURLOPT_URL, $this->service_url.'user/'.$id_user);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
//$body = '{}';
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
//curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
这篇关于PHP cURL GET请求和请求的正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!