Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

How can I connect to a API service using curl in php?

I'm trying to connect to a API service using the following php:

$url = 'https://api.wlvpn.com/v2/customers&api-key=my-api-key'
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROXY, "http://127.0.0.1/");
$output = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);

print_r($output);
print_r($curl_error);

when I run it I get the following error:

couldn't connect to host

However, when I run the following command from my command line in ubuntu:

jai@ubuntu:/opt/lampp$  curl -u api-key:my-api-key https://api.wlvpn.com/v2/customers

I get a response as expected

Can anyone help me what I am missing here I think I am missing -u option but I dont have any idea how to put it on my php code

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is your expected answer. The url isn't correct, because you're using & instead of ?. And then you're telling cURL to connect to a proxy on 127.0.0.1 (there is none, usually). And the ssl certificate is self-signed, so you have to set CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER to 0 and false.

This script works:

<?php
$url = 'https://api.wlvpn.com/v2/customers?api-key=my-api-key';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);

print_r($output);
print_r($curl_error);
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...