php - 创建函数以向 API 发送请求
问题描述
我有一个 API,我正在尝试创建一个函数来发送请求,文档在这里:http ://simportal-api.azurewebsites.net/Help
我想过在 PHP 中创建这个函数:
function jola_api_request($url, $vars = array(), $type = 'POST') {
$username = '***';
$password = '***';
$url = 'https://simportal-api.azurewebsites.net/api/v1/'.$url;
if($type == 'GET') {
$call_vars = '';
if(!empty($vars)) {
foreach($vars as $name => $val) {
$call_vars.= $name.'='.urlencode($val).'&';
}
$url.= '?'.$call_vars;
}
}
$ch = curl_init($url);
// Specify the username and password using the CURLOPT_USERPWD option.
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
if($type == 'POST') {
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
}
// Tell cURL to return the output as a string instead
// of dumping it to the browser.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Execute the cURL request.
$response = curl_exec($ch);
// Check for errors.
if(curl_errno($ch)){
// If an error occured, throw an Exception.
//throw new Exception(curl_error($ch));
$obj = array('success' => false, 'errors' => curl_error($ch));
} else {
$response = json_decode($response);
$obj = array('success' => true, 'response' => $response);
}
return $obj;
}
因此,这决定了它是 GET 请求还是 POST 请求,但某些调用返回的响应是不支持 GET 或不支持 POST,尽管我为每个调用指定了正确的请求。
我认为我的功能以某种方式出错,并想知道是否有人可以帮助我朝正确的方向前进?正如我也注意到的,我也需要允许 DELETE 请求。
解决方案
为了更轻松的生活,请尝试 guzzle。 http://docs.guzzlephp.org/en/stable/
你可以提出这样的请求:
use GuzzleHttp\Client;
$client = new Client();
$myAPI = $client->request('GET', 'Your URL goes here');
$myData = json_decode($myAPI->getBody(), true);
然后你可以像数组一样访问数据
$myData["Head"][0]
推荐阅读
- flutter - 颤振中的ffmpeg音频转换
- nd4j - 如何将较小的 INDArray 复制到较大的 INDArray
- java - Java 使用 MongoCollection.countDocuments() 执行缓慢甚至超时,但不推荐使用 count() 方法是可以的
- kubernetes - Helm 和 Kustomize 有什么区别?
- excel - 提取两个特定字符或数字之间的单词
- ruby - 如果消息为空,则 Logstash 删除整行
- angular - 订阅者内部的订阅者在离子项目中无法正常工作
- java - 由于 GSON 库中的 CLOB 数据类型导致的异常
- javascript - 我有一个问题 javascript 切换索引
- react-native - 在 IOS 13 中从服务器获取消息时未设置徽章