PHp + socket编程练习回复

因为也是学习的路上,先画出思路,代码和看别人的学习的,最后是根据的思路完成的,可能比较简单,后期在去完善和更改

<?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);



郑重声明:本文版权包含图片归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们(delete@yzlfxy.com)修改或删除,多谢。

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

留言与评论(共有 0 条评论)
昵称:
匿名发表
   
验证码: