php socket 发送http请求 GET POST

52 篇文章 0 订阅
7 篇文章 0 订阅

  http://docs.php-http.org/en/latest/httplug/users.html

<?php
/**
 * Created by PhpStorm.
 * User: Mch
 * Date: 7/8/18
 * Time: 21:39
*/

interface Proto {
    // 连接url
    public function conn($url);
    //发送get查询
    public function get();
    // 发送post查询
    public function post();
    // 关闭连接
    public function close();
}

class Http implements Proto {

    const CRLF  = "\r\n";
    const BUFFSIZE = 1024;

    protected $errno = -1;
    protected $errstr = '';
    protected $response = '';

    protected $url = [];
    protected $version = 'HTTP/1.1';
    protected $fh = null;

    protected $line = [];
    protected $header = [];
    protected $body = [];

    public function __construct($url) {
        $this->conn($url);
        $this->setHeader('Host: ' . $this->url['host']);
    }

    // POST /student/login HTTP/1.1
    protected function setLine($method) {
        $query = $this->url['query'];
        $this->line[0] = implode(' ', [
            $method,
            $this->url['path'].(strlen($query)>0 ? '?'.$query : ''),
            $this->version
        ]);
    }

    public function setHeader($headerline) {
        $this->header[] = $headerline;
    }

    public 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;
        }
        if(!isset($this->url['query'])) {
            $this->url['query'] = '';
        }
        $this->fh = fsockopen($this->url['host'],
            $this->url['port'],
            $this->errno,
            $this->errstr,
            3   /* timeout 3s */
        );
        if (!$this->fh) {
            echo "$this->errstr ($this->errno)";
            return NULL;
        }
        return $this->fh;
    }

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

    // 构造post查询的数据
    public function post($body = [], $enctype = 'application/x-www-form-urlencoded') {
        $this->setLine('POST');
        // content-type 'multipart/form-data' or ...
        $this->setHeader('Content-type: ' . $enctype . '; charset=UTF-8');

        $this->setBody($body);
        $this->setHeader('Content-length: ' . strlen($this->body[0]));

        $this->request();
        return $this->response;
    }

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

    // 真正请求
    private function request() {
        // 把请求行,头信息,实体信息 放在一个数组里,便于拼接
        fwrite($this->fh, implode(self::CRLF, array_merge(
            $this->line,
            $this->header,
            [''],
            $this->body,
            ['']
        )));

        // 为什么循环第2次时候很慢(假设响应长度<BUFFSIZE, 即1次读取完了)?
        while(!feof($this->fh)) {
            $content = fread($this->fh, self::BUFFSIZE);
            if (strlen($content)<=0) {
                break;
            }
            $this->response .= $content;
            // echo $this->response;
        }
    }

}

// $url = "http://www.tfjyzx.com/news/listTVProgram?area=%E8%AE%B8%E6%98%8C";
$url = "http://www.tfjyzx.com/student/login";
$http = new Http($url);

// $resp = $http->get();
$http->setHeader('X-Requested-With: XMLHttpRequest');
$http->setHeader('User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36');
// !important $.ajax() contentType: 'application/json'
$http->setHeader('Accept: application/json, text/javascript, */*; q=0.01');

// 'username=mingzhanghui&pwd=123456&captcha=&count=1'
$resp = $http->post([
    'username' => 'mingzhanghui',
    'pwd' => '123456',
    'captcha' => '',
    'count' => 1
]);
var_dump($http);
$http->close();

echo $resp;
@func: parse_url
http://www.tfjyzx.com/model-school.jsp?area=%E5%BC%80%E5%B0%81&school=%E5%BC%80%E5%B0%81%E5%B8%82%E7%AC%AC%E4%BA%94%E4%B8%AD%E5%AD%A6#%E5%AD%A6%E6%A0%A1%E7%AE%80%E4%BB%8B

array(5) {
["scheme"]=>
string(4) "http"
["host"]=>
string(14) "www.tfjyzx.com"
["path"]=>
string(17) "/model-school.jsp"
["query"]=>
string(94) "area=%E5%BC%80%E5%B0%81&school=%E5%BC%80%E5%B0%81%E5%B8%82%E7%AC%AC%E4%BA%94%E4%B8%AD%E5%AD%A6"
["fragment"]=>
string(36) "%E5%AD%A6%E6%A0%A1%E7%AE%80%E4%BB%8B"
}

可以使用现有的库: php-http
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fareast_mzh

打赏个金币

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值