PHP Socket连接到API
问题描述:
我正在尝试使用PHP套接字连接到API。PHP Socket连接到API
我已经在很多方面尝试过,但我无法得到它的工作。我知道还有其他的答案,但是没有人能工作。我真的无法实现它。我至少在两天内尝试。
以下是错误:
php_network_getaddresses: getaddrinfo failed: Name or service not known
代码(套接字 - 它不工作):
var $url = 'api.site.com.br/';
public function getUsers(){
$path = "users/?accesstoken=c24f506fe265488435858925096bc4ad7ba0";
$packet= "GET {$path} HTTP/1.1\r\n";
$packet .= "Host: {$url}\r\n";
$packet .= "Connection: close\r\n";
if (!($socket = fsockopen($this->url,80,$err_no,$err_str))){
die("\n Connection Failed. $err_no - $err_str \n");
}
fwrite($socket, $packet);
return stream_get_contents($socket);
}
代码(卷曲 - 它的作品!):
public function getUsers2(){
$path = "users/?accesstoken=c24f506fe265488435858925096bc4ad7ba0";
$method = 'GET';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url . $path);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
$output = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);
return $output;
}
我不能给你正确的URL,但URL与Curl一起工作,所以它应该与套接字一起工作。
答
我解决它通过执行以下操作:
public function getUsers(){
$path = "users/?accesstoken=c24f506fe265488435858925096bc4ad7ba0";
$fp = fsockopen($this->url, 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET /{$path} HTTP/1.1\r\n";
$out .= "Host: {$this->url}\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
}
答
通过插座连接到主机没有连接到一个URL。
错误:api.site.com.br/
错误:http://api.site.com.br/
错误:https//api.site.com.br/api/
右:api.site.com.br
您连接到主机。这可以是域名或IP。这两者都没有斜线。
这不是问题所在。 – Alan