http--发送get请求获取网页


写入网页地址,调用get方法,获得响应


<?php
/*php+socket编程 发送http
http类 操作案例get--获取网页 post批量发帖 */

// 类似fopen,fwrite输入内容进txt文件
interface Proto{
	//连接
	function conn($url);

	//发送get
	function get();

	//发送post
	function post();

	//关闭
	function close();

}


//* 继承的东西全要继承不能不写
class Http implements Proto{
	protected $url=null;
	protected $line=array();
	protected $header=array();
	protected $body=array();

	protected $fh=NULL;
	protected $version="HTTP/1.1";
	protected $errno= -1;
	protected $errstr='';
	protected $resp='';//响应
	const CRLF="\r\n";


	//* 一开始就需要的变量 填在construct里
	public function __construct($url){
		$this->conn($url);
		$this->setHeader();//本来写在get方法,但所有请求方法header相同
	}

	//连接,得到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'],$this->errno,$this->errstr,10);
	// resource fsockopen ( string $hostname [, int $port = -1 [,
	 // int &$errno [, string &$errstr [, float $timeout 
	 // = ini_get("default_socket_timeout") ]]]] )
	// 初始化一个套接字连接到指定主机(hostname)。也就是打开了通道可以读取写入进这个网站
	}


	//发送get *怎么get写在$line前面 setline方法设一个变量,在不同请求方法里用
	public function get(){
		$this->setLine('GET');
		$this->request();
		return $this->resp;
	}

	//发送post
	public function post(){

	}

	// 请求拼接发送 *怎么整合 请求数组变成str
	public function request(){
		$req=array_merge($this->line,$this->header,array(''),$this->body,array(''));
		$req=implode(self::CRLF, $req);//crlf换行
		// echo $req;
		// 写入请求*
		fwrite($this->fh, $req);
		while (!feof($this->fh)) {
			$this->resp.=fread($this->fh, 1024);
		}
		// $this->close();

	}

	//关闭
	public function close(){

	}

	// 拼接 请求行1
	protected function setLine($method){
		$this->line[]=$method." ".$this->url['path']." ".$this->version;

	}

	//请求头部2
	protected function setHeader(){
		$this->header[]="Host:".$this->url['host'];

	}


	//请求主体部分3
	protected function setBody(){

	}

}


$http=new Http('http://news.qq.com/a/20160107/019440.htm');
// url====[scheme] => http [host] => news.163.com [path] => /16/0107/06/BCN66S6S00014AED.html 

echo $http->get();
//line === Array ( [0] => GET /16/0107/06/BCN66S6S00014AED.html HTTP/1.1 ) 
//header === Array ( [0] => Host:news.163.com )
// $http->request();

?>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值