目录
php 利用socket发送HTTP请求(GET,POST),socketget
首页 php教程 php手册 php 利用socket发送HTTP请求(GET,POST),socketget

php 利用socket发送HTTP请求(GET,POST),socketget

Jun 13, 2016 am 08:55 AM
http请求 php socket

php 利用socket发送HTTP请求(GET,POST),socketget

  今天给大家带来的是如何利用socket发送GET,POST请求。我借用燕十八老师封装好的一个Http类给进行说明。

  在日常编程中相信很多人和我一样大部分时间是利用浏览器向服务器提出GET,POST请求,那么可否利用其它方式提出GET,POST请求呢?答案必然是肯定的。了解过HTTP协议的人知道,浏览器提交请求的实质是向服务器发送一个请求信息,这个请求信息有请求行,请求头,请求体(非必须)构成。服务器根据请求信息返回一个响应信息。连接断开。

   HTTP请求的格式如下所示:

<request-line>
<headers>
<blank line>
[<request-body>]

登录后复制

  HTTP响应的格式与请求的格式十分相似:

<status-line>
<headers>
<blank line>
[<response-body>]
登录后复制

  我们可以利用HTTP发送请求的原理,可以重新考虑利用socket发送HTTP请求。

  Socket的英文原义是“孔”或“插座”。通常也称作“套接字”,用于描述IP地址和端口,是一个通信链的句柄,可以用来实现不同虚拟机或不同计算机之间的通信。在Internet上的主机一般运行了多个服务软件,同时提供几种服务。每种服务都打开一个Socket,并绑定到一个端口上,不同的端口对应于不同的服务。如此看来,其实利用socket操作远程文件和读写本地的文件一样容易,把本地文件看成通过硬件传输,远程文件通过网线传输就行了。

  因而可以将发送请求的考虑成 建立连接->打开socket接口(fsockopen())->写入请求(fwrite())->读出响应(fread()->关闭文件(fclose())。话不多说,直接上代码:

<&#63;php 
interface Proto {
  // 连接url
  function conn($url);
  //发送get查询
  function get();
  // 发送post查询
  function post();
  // 关闭连接
  function close();
}
class Http implements Proto {
  const CRLF = "\r\n";
  protected $errno = -1;
  protected $errstr = '';
  protected $response = '';
  protected $url = null;
  protected $version = 'HTTP/1.1';
  protected $fh = null;
  protected $line = array();
  protected $header = array();
  protected $body = 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'] . '&#63;' .$this->url['query'] . ' '. $this->version;
  }
  // 此方法负责写头信息
  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;
    }
    // 判断query
    if(!isset($this->url['query'])) {
      $this->url['query'] = '';
    }
    $this->fh = fsockopen($this->url['host'],$this->url['port'],$this->errno,$this->errstr,3);
  }
  //构造get请求的数据
  public function get() {
    $this->setLine('GET');
    $this->request();
    return $this->response;
  }
  // 构造post查询的数据
  public function post($body = array()) {   
    $this->setLine('POST');
    // 设计content-type
    $this->setHeader('Content-type: application/x-www-form-urlencoded');
    // 设计主体信息,比GET不一样的地方
    $this->setBody($body);
    // 计算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);
    $req = implode(self::CRLF,$req); 
    //echo $req; exit;
    fwrite($this->fh,$req);
    while(!feof($this->fh)) {
      $this->response .= fread($this->fh,1024);
    }
    $this->close(); // 关闭连接
  }
  // 关闭连接
  public function close() {
    fclose($this->fh);
  }
}

登录后复制

利用此类发送一个简单的GET请求:

<&#63;php
//记得引用Http类
$url="http://home.jb51.net/u/DeanChopper/";
$http=new Http($url);
$response=$http->get();
print_r($response);

登录后复制

  返回值为信息,可以对响应信息进行进一步处理,得到自己想得到的内容。

我们来看下一个具体的实例

<&#63;php
/**
 * 使用PHP Socket 编程模拟Http post和get请求
 * @author koma
 */
class Http{
  private $sp = "\r\n"; //这里必须要写成双引号
  private $protocol = 'HTTP/1.1';
  private $requestLine = "";
  private $requestHeader = "";
  private $requestBody = "";
  private $requestInfo = "";
  private $fp = null;
  private $urlinfo = null;
  private $header = array();
  private $body = "";
  private $responseInfo = "";
  private static $http = null; //Http对象单例
   
  private function __construct() {}
   
  public static function create() {
    if ( self::$http === null ) { 
      self::$http = new Http();
    }
    return self::$http;
  }
   
  public function init($url) {
    $this->parseurl($url);
    $this->header['Host'] = $this->urlinfo['host'];
    return $this;
  }
   
  public function get($header = array()) {
    $this->header = array_merge($this->header, $header);
    return $this->request('GET');
  }
   
  public function post($header = array(), $body = array()) {
    $this->header = array_merge($this->header, $header);
    if ( !empty($body) ) {
      $this->body = http_build_query($body);
      $this->header['Content-Type'] = 'application/x-www-form-urlencoded';
      $this->header['Content-Length'] = strlen($this->body);
    }
    return $this->request('POST');
  }
   
  private function request($method) {
    $header = "";
    $this->requestLine = $method.' '.$this->urlinfo['path'].'&#63;'.$this->urlinfo['query'].' '.$this->protocol;
    foreach ( $this->header as $key => $value ) {
      $header .= $header == "" &#63; $key.':'.$value : $this->sp.$key.':'.$value;
    }
    $this->requestHeader = $header.$this->sp.$this->sp;
    $this->requestInfo = $this->requestLine.$this->sp.$this->requestHeader;
    if ( $this->body != "" ) {
      $this->requestInfo .= $this->body;
    }
    /*
     * 注意:这里的fsockopen中的url参数形式为"www.xxx.com"
     * 不能够带"http://"这种
     */
    $port = isset($this->urlinfo['port']) &#63; isset($this->urlinfo['port']) : '80';
    $this->fp = fsockopen($this->urlinfo['host'], $port, $errno, $errstr);
    if ( !$this->fp ) {
      echo $errstr.'('.$errno.')';
      return false;
    }
    if ( fwrite($this->fp, $this->requestInfo) ) {
      $str = "";
      while ( !feof($this->fp) ) {
        $str .= fread($this->fp, 1024);
      }
      $this->responseInfo = $str;
    }
    fclose($this->fp);
    return $this->responseInfo;
  }
   
  private function parseurl($url) {
    $this->urlinfo = parse_url($url);
  }
}
// $url = "http://news.163.com/14/1102/01/AA0PFA7Q00014AED.html";
$url = "http://localhost/httppro/post.php";
$http = Http::create()->init($url);
/* 发送get请求 
echo $http->get(array(
  'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36',
));
*/
 
/* 发送post请求 */
echo $http->post(array(
    'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36',
), array('username'=>'发一个中文', 'age'=>22));
登录后复制

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

适用于 Ubuntu 和 Debian 的 PHP 8.4 安装和升级指南 适用于 Ubuntu 和 Debian 的 PHP 8.4 安装和升级指南 Dec 24, 2024 pm 04:42 PM

PHP 8.4 带来了多项新功能、安全性改进和性能改进,同时弃用和删除了大量功能。 本指南介绍了如何在 Ubuntu、Debian 或其衍生版本上安装 PHP 8.4 或升级到 PHP 8.4

CakePHP 使用数据库 CakePHP 使用数据库 Sep 10, 2024 pm 05:25 PM

在 CakePHP 中使用数据库非常容易。本章我们将了解CRUD(创建、读取、更新、删除)操作。

CakePHP 日期和时间 CakePHP 日期和时间 Sep 10, 2024 pm 05:27 PM

为了在 cakephp4 中处理日期和时间,我们将使用可用的 FrozenTime 类。

CakePHP 文件上传 CakePHP 文件上传 Sep 10, 2024 pm 05:27 PM

为了进行文件上传,我们将使用表单助手。这是文件上传的示例。

讨论 CakePHP 讨论 CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP 是 PHP 的开源框架。它的目的是使应用程序的开发、部署和维护变得更加容易。 CakePHP 基于类似 MVC 的架构,功能强大且易于掌握。模型、视图和控制器 gu

CakePHP 创建验证器 CakePHP 创建验证器 Sep 10, 2024 pm 05:26 PM

可以通过在控制器中添加以下两行来创建验证器。

CakePHP 日志记录 CakePHP 日志记录 Sep 10, 2024 pm 05:26 PM

登录 CakePHP 是一项非常简单的任务。您只需使用一项功能即可。您可以记录任何后台进程(如 cronjob)的错误、异常、用户活动、用户采取的操作。在 CakePHP 中记录数据很容易。提供了 log() 函数

如何设置 Visual Studio Code (VS Code) 进行 PHP 开发 如何设置 Visual Studio Code (VS Code) 进行 PHP 开发 Dec 20, 2024 am 11:31 AM

Visual Studio Code,也称为 VS Code,是一个免费的源代码编辑器 - 或集成开发环境 (IDE) - 可用于所有主要操作系统。 VS Code 拥有针对多种编程语言的大量扩展,可以轻松编写

See all articles