您好,我正在使用 API。 API 文档中明确写道,所有数据均以 JSON 形式发送和接收,并采用 UTF-8 编码。之后他们给出了一行
$ curl --user name:password https://api.abc.de/erer
我只是想问我如何发送上面提到的curl请求?用户名和密码将作为 GET
、POST
或在 headers
中发送?
我正在使用以下代码,但收到空数组。文档说它必须接收一些错误或成功代码。
$ch = curl_init();
$post_data = array('username'=>$_POST['username'],'password'=>$_POST['password']);
$post_data = http_build_query($post_data);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'username:password');
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
$result = (array) $result;
echo "<pre>";
print_r($result);
echo "</pre>";
die();
我已经打印出 curl_get_info
的响应,即
Array
(
[url] => https://api.abc.de/erer
[content_type] =>
[http_code] => 0
[header_size] => 0
[request_size] => 0
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0
[namelookup_time] => 0.618462
[connect_time] => 0
[pretransfer_time] => 0
[size_upload] => 0
[size_download] => 0
[speed_download] => 0
[speed_upload] => 0
[download_content_length] => 0
[upload_content_length] => 0
[starttransfer_time] => 0
[redirect_time] => 0
)
最佳答案
根据提供的信息,假设您正在发出 POST 请求,类似的操作应该可以工作:
$post_data = http_build_query( $post_array );
$url = 'https://api.abc.de/erer';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, 'name:password');
$data = curl_exec( );
curl_close($ch);
$post_data 应包含要发送的 key => 值的关联数组。 我相信您的用户名:密码已在 header 中发送,但 PHP.net 没有说明。
关于php - 我将如何编写这个curl请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12819258/