如何使用 PHP 通过 cURL 向 REST API 发送 HTTP GET 请求,并使用 cURL 从 REST API 调用方法 [英] How to send HTTP GET request to REST API via cURL using PHP and call method from REST API with cURL
问题描述
我正在使用 PHP
和 cURL
.
我想向 REST
API
发送 HTTP GET
请求,并且我想从 REST API
调用方法.
如何使用 PHP
通过 cURL
制作?我有 API
URL
和密钥.
我必须用 URL 发送我的密钥,我需要 REST API
中的方法.
我需要做什么?
同时,我必须对所有请求发送基本身份验证,然后才能获得 JSON
数据.
我该怎么做?
I'm using PHP
and cURL
.
I want to send HTTP GET
request to REST
API
and I want to call method from REST API
.
How can i make via cURL
using PHP
? I have API
URL
and Key.
I must send my key with URL and I need method inside REST API
.
What I need to do?
At the same time, i have to send basic authentication on all requests and I'll get JSON
data.
How can i do?
谢谢.问候
这是我的代码
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $username.':'.$password);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Content-Type: application/json')
);
$result = curl_exec($ch);
curl_close($ch);
推荐答案
我已经尝试过你的代码并将变量更改为数组.添加了 httpheaders、useragents.并保存到 cookie 和 cookie 位置.并经过测试:
I have tried your code and changed variables into array. Added httpheaders, useragents. And save to cookies and cookie location. And tested:
$username = "username";
$password = "password";
$url = "http://localhost/html/login";
$send = "?username=".$username."&password=".$password;
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_VERBOSE => 1,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0',
CURLOPT_POST => true,
CURLOPT_USERNAME, $username,
CURLOPT_USERPWD, $password,
CURLOPT_POSTFIELDS => $send,
CURLOPT_SSL_VERIFYPEER, false,
CURLOPT_HEADER => 1,
CURLOPT_HTTPHEADER => array(
"Accept-Language: en-US;q=0.6,en;q=0.4",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Connection: keep-alive"
),
CURLOPT_COOKIEFILE => "cookies.txt",
CURLOPT_COOKIEJAR => "cookies.txt",
CURLOPT_REFERER => "http://localhost/html/login",
CURLOPT_ENCODING => 'gzip,deflate'
)); //gzip, if modul on
curl_exec($ch);
curl_close($ch);
这篇关于如何使用 PHP 通过 cURL 向 REST API 发送 HTTP GET 请求,并使用 cURL 从 REST API 调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!