标签:des blog http io os ar for strong sp
因为也是学习的路上,先画出思路,代码和看别人的学习的,最后是根据的思路完成的,可能比较简单,后期在去完善和更改
<?php
/**
* php+socket 编程 发送HTTP请求
* @version c.php
* 模拟博客园评论
*/
interface Proto{
// 连接url
public function conn($url);
// 发送get请求
public function get();
// 发送post请求
public function post($body);
//关闭连接
public function close();
}
class Http implements Proto{
protected $response = ‘‘;
protected $fh=null;
protected $errno = -1;
protected $errorstr = ‘‘;
protected $line = array();
protected $header = array();
protected $body = array();
public $url = array();
public function __construct($url){
$this->conn($url);
$this->setHeader(‘Host: ‘ . $this->url[‘host‘]);
}
// 请求行
protected function setLine($method){
$this->line[0] = $method . ‘ ‘ . $this->url[‘path‘] . ‘ ‘ . ‘HTTP/1.1‘;
}
// 头信息
public function setHeader($headerline){
$this->header[] = $headerline;
}
// 主体信息
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‘],$this->errno,$this->errorstr,3);
}
// 构建get请求
public function get(){
$this->setLine(‘GET‘);
$this->request();
return $this->response;
}
// 发送post请求
public function post($bo){
$this->setLine(‘POST‘);
// content-type
$this->setHeader("Content-type: application/x-www-form-urlencoded");
$this->setBody($bo);
// content-length
$this->setHeader("Content-length: " .strlen($this->body[0]));
$this->request();
return $this->response;
}
public function request(){
$req = array_merge($this->line,$this->header,array(‘‘),$this->body,array(‘‘));
//print_r($req);die;
$req = implode(PHP_EOL,$req); // PHP_EOL 换行
// echo $req;die;
fwrite($this->fh,$req);
while(!feof($this->fh)){
$this->response .= fread($this->fh,1024);
}
$this->close();
}
public function close(){
fclose($this->fh);
}
}
上面是简单的类
<?php
require("./c.php"); // 引入上面的类
$url = "http://www.cnblogs.com/mvc/PostComment/Add.aspx";
$http = new Http($url);
$http->setHeader("Cookie:xxxx");
$http->setHeader("Referer: http://www.cnblogs.com/geek12/p/4024793.html");
$http->setHeader("User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0");
$msg =array(
"blogApp"=>"geek12",
"body"=>"来自robot",
"parentCommentId"=>0,
"postId"=>4024793);
$http->post($msg);
发送成功的截图
在写的过程中遇到的几个问题,根据请求的url 不一样,请求头的拼接也需要改变,这里请求的url是 http://www.cnblogs.com/mvc/PostComment/Add.aspx 静态的连接,所有path 直接拿到后面的,如果是动态的就需要修改了,所以本方法只适合静态的连接,动态的需要修改请求头
不是所有的网站都可以模拟,虽然没有验证码,我在VeryCd 网站,怎么模拟都没有成功,最后只好放弃了
我是菜鸟,请不要抨击,待续。。。。
标签:des blog http io os ar for strong sp
原文地址:http://www.cnblogs.com/geek12/p/4028623.html