php发起http请求代码

<?php

interface Proto
{
    
    
    // 连接url
    public function conn($url);

    // 发送get
    function get();

    // 发送post
    function post();

    // 关闭连接
    function close();
}

class Http implements Proto
{
    
    

    const CRLF = "\r\n"; // http标准换行符
    protected $line = array();
    protected $header = array();
    protected $body = array();
    protected $url = array();
    protected $version = 'HTTP/1.1';
    protected $fh = null;
    protected $errno = -1;
    protected $errstr = '';
    protected $res = '';
    public function __construct($url)
    {
    
    
        $this->conn($url);
        $this->setHeader('Host: ' . $this->url['host']);

    }
    // 复制写请求行
    protected function setLine($method)
    {
    
    
        $this->line[0] = $method . ' ' . $this->url['path'].'?'.$this->url['query']. ' ' . $this->version;
    }
    // 写头信息
    protected function setHeader($headerLine)
    {
    
    
        $this->header[] = $headerLine;
        // 'HOST: '.$this->url['host']
    }
    // 写主体信息
    protected function setBody($body)
    {
    
    
        $this->body = (http_build_query($body));
    }
    // 连接url
    public function conn($url)
    {
    
    
        $this->url = parse_url($url);
        // 判断端口
        if (!isset($this->url['port'])) {
    
    
            $this->url['port'] = 80;
        }

        $this->fh = fsockopen($this->url['host'], $this->url['port'], $errno, $errstr, 3);
    }

    //  构造get请求
    public function get()
    {
    
    
        $this->setLine('GET');
        $this->request();
        return $this->res;
    }

    // 构造post请求
    public function post($body = array())
    {
    
    
        // 构造主体信息
        $this->setLine('POST');

        $this->setBody($body);

         // 设置content-type
        $this->setHeader('Content-type: application/x-www-form-urlencoded');
        // 计算content-length
        $this->setHeader('Content-length: '.strlen($this->body));
       
       
        $this->request();
        // return $this->res;
    }

    // 发起请求
    public function request()
    {
    
    
        // 将请求行、头信息、实体信息放在一个数组便于拼接
        $req = array_merge($this->line, $this->header, array(''), array($this->body), array(''));
        $req = implode(self::CRLF, $req);
        //    echo $req;
        fwrite($this->fh, $req);

        // echo $req;
        // exit;
        while (!feof($this->fh)) {
    
    
            // 一次读1024 fh没到结尾
            $this->res .= fread($this->fh, 1024);
        }
        $this->close();

    }
    // 关闭连接
    public function close()
    {
    
    
        fclose($this->fh);
    }
}

$url = 'http://localhost:8081/post.php';
$http = new Http($url);

$http->post(array('name'=>'mike','age'=>'18'));

Guess you like

Origin blog.csdn.net/weixin_42043407/article/details/117030961