详解http协议

来源:互联网 发布:巨人网络股票估值多少 编辑:程序博客网 时间:2024/04/28 12:21


 简介:

超文本传输协议(HTTP,HyperText Transfer Protocol)是互联网上应用最为广泛的一种网络协议.

简单理解就是一种约定,比如你跟别人说你吃了吗,别人会回应你一下吃了或者没吃....


看下客户端和服务器流程图:


 用户(客户端)发起http请求到服务器通过apache或nginx解析以后返回结果给客户端.....大概就是这个意思!


<?php /**  *  使用socket发送GET请求  *  请求报文包括三个部分  请求行   请求头    请求体  * fwrite ------- 把 string 的内容写入 文件指针 handle 处   int fwrite ( resource $handle , string $string [, int $length ] )  *  feof ----测试文件指针是否到了文件结束的位置  bool feof ( resource $handle )  *  fgets — 从文件指针中读取一行   string fgets ( resource $handle [, int $length ] )  *///创建连接  $fp = fsockopen('localhost', 80, $errno, $errstr, 10);//检测连接是否成功if(!$fp) {echo $errstr;die;}//拼接http请求报文$http = '';$http .= "GET /http/server.php?uid=100&name=jg HTTP/1.1\r\n";//请求行包括三个部分  请求方式  请求脚本的绝对路径   协议的版本$http .= "Host: localhost\r\n";  //请求头信息   主机名$http .= "Connection: close\r\n\r\n";//keep-alive    //连接状态设置 close表示连接完成后关闭  keep-alive表示使客户端到服务器端的连接持续有效//请求体  无//发送请求 fwrite($fp, $http);$res = ''; // 获取结果 while(!feof($fp)) {$res .= fgets($fp);}//输出内容echo $res;


返回结果:


HTTP/1.1 200 OK     //响应行
//响应头
Date: Tue, 19 Jul 2016 11:51:14 GMT
Server: Apache/2.4.17 (Win32) PHP/5.6.15
X-Powered-By: PHP/5.6.15
Content-Length: 16
Connection: close
Content-Type: text/html; charset=UTF-8


//响应体
iloveyouverymuch



代码原理图:

  

 

<?php /**  *  使用socket发送POST请求  *  请求报文包括三个部分  请求行   请求头    请求体  * fwrite ------- 把 string 的内容写入 文件指针 handle 处   int fwrite ( resource $handle , string $string [, int $length ] )  *  feof ----测试文件指针是否到了文件结束的位置  bool feof ( resource $handle )  *  fgets — 从文件指针中读取一行   string fgets ( resource $handle [, int $length ] )  *///创建连接$fp = fsockopen('localhost', 80, $errno, $errstr, 10);//判断if(!$fp) {echo $errstr;die;}$http = '';//请求行$http .= "POST /class/Public/laravel/http/server.php HTTP/1.1\r\n";//请求头$http .= "Host: localhost\r\n";$http .= "Connection: close\r\n";$http .= "Cookie: username=admin;uid=200\r\n";$http .= "User-agent: firefox-chrome-safari-ios-android\r\n";$http .= "Content-type: application/x-www-form-urlencoded\r\n";$http .= "Content-length: 37\r\n\r\n";//请求体$http .= "email=xiaohigh@163.com&username=admin\r\n";//发送fwrite($fp, $http);$res = '';//获取结果while(!feof($fp)) {$res .= fgets($fp);}echo $res;



1 0
原创粉丝点击