PHP cURL GET 请求和请求的正文 [英] PHP cURL GET request and request's body

查看:38
本文介绍了PHP cURL GET 请求和请求的正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 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?

因为这个完整代码与 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 请求的主体(payload).对于 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆