【发布时间】:2020-01-14 03:16:08
【问题描述】:
我有一个 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 或某种久经考验的库来为您完成所有繁重的工作?
-
你试过用邮递员或其他程序检查url或请求是否正确吗?
-
如果服务器响应“GET is not supported or POST is not supported”,那么你只是简单地为API设置了错误的HTTP方法
-
您能与我们分享您使用什么作为函数的参数吗?