socket发送get请求
使用GET采集163网站新闻信息###
<?php
/**
PHP+scoket编程 发送HTTP请求
使用GET采集网站信息
**/
//http请求类接口
interface Prote{
//连接url
function conn($url);
//发送get查询
function get();
//发送post查询
function post();
//关闭连接
function close();
}
class Http implements Prote{
const CRLF = "\r\n"; //声明一个换行常量
protected $errno = -1;
protected $errstr = '';
protected $response = '';
protected $fh = null;
protected $url = array(); //存放url信息
protected $line = array(); //放置请求行
protected $header = array(); //放置头信息
protected $body = array(); //放置主体信息
public function __construct($url){
$this->conn($url);
$this->setHeader('Host:' . $this->url['host']);
}
/**
* [setLine 此方法负责写请求行]
* @param [str] $method [description]
*/
protected function setLine($method){
$this->line[0] = $method . ' ' .$this->url['path'] . ' ' . 'HTTP/1.1';
}
/**
* [setHeader 此方法负责写头信息]
* @param [type] $headerline [头信息]
*/
protected function setHeader($headerline){
$this->header[] = $headerline;
}
//此方法负责写主体信息
protected function setBody(){
}
/**
* [conn 连接url]
* @param [type] $url [请求的地址]
* @return [type] [description]
*/
public function conn($url){
$this->url = parse_url($url); //分析$url
// 判断端口
if(!isset($this->url['port'])){
$this->url['port'] = 80;
}
$this->fh = fsockopen($this->url['host'],$this->url['port'],$this->errno,$this->errstr,3);
print_r($this->fh);
}
/**
* [get 构造get请求的数据]
* @return [type] [description]
*/
public function get(){
$this->setLine('GET');
$this->request();
return $this->response;
}
/**
* [post 构造post查询的数据]
* @return [type] [description]
*/
public function post(){
}
/**
* [request 真正请求]
* @return [type] [description]
*/
public function request(){
//把请求行、头信息、实体信息 放在一个数组中,便于拼接
$req = array_merge($this->line,$this->header,array(''),$this->body,array(''));
$req = implode(self::CRLF,$req);
/**
* 请求信息拼接结果
* GET /17/0223/08/CDUQ91V100097U7T.html HTTP/1.1
* Host: tech.163.com
*
*
*/
fwrite($this->fh,$req);
while(!feof($this->fh)){
$this->response .= fread($this->fh,1024);
}
$this->close(); //关闭连接
}
/**
* 换行:
* linux:\r
* mac : \n
* window : \r\n
* http标准协议:\r\n
*/
//关闭连接
public function close(){
}
}
$url = "http://tech.163.com/17/0223/08/CDUQ91V100097U7T.html";
$http = new Http($url);
echo $http->get();