PHP encapsulated HttpClient Class usage examples, encapsulating httpclient_php tutorials

Source: Internet
Author: User

PHP encapsulated HttpClient Class Usage example, package httpclient


The examples in this article describe the HttpClient class for PHP encapsulation. Share to everyone for your reference. The specific analysis is as follows:

This is a PHP encapsulated HttpClient class that enables simple functions such as Get POST Cookie session. Originally done, these two days re-modified a bit.

<?php */* Filename:httpclient.php * Created on 2012-12-21 * Created by Robintang * To change the template for thi S generated file go to * window-preferences-phpeclipse-php-code Templates */class Sincookie {public $name; /cookie name public $value; Cookie value//The following three properties do not now implement public $expires; Expiration time public $path; Path public $domain;       Domain//Create a cookie object from the cookie string function __construct ($s = false) {if ($s) {$i 1 = strpos ($s, ' = ');       $i 2 = Strpos ($s, '; ');       $this->name = Trim (substr ($s, 0, $i 1));     $this->value = Trim (substr ($s, $i 1 +1, $i 2-$i 1-1));   }}//Get cookie Key value pair function Getkeyvalue () {return "$this->name= $this->value";  }}//session context class Sinhttpcontext {public $cookies;//session cookies public $referer;//Previous page address function __construct ()     {$this->cookies = array ();   $this->refrer = "";     }//Set cookie function cookie ($key, $val) {$ck = new Sincookie (); $ck->name = $key;     $ck->value = $val;   $this->addcookie ($CK);   }//Add Cookie function Addcookie ($ck) {$this->cookies[$ck->name] = $ck;     }//Get the cookie string, use function cookiesstring () {$res = ' "when requested; foreach ($this->cookies as $ck) {$res. = $ck->getkeyvalue ().     ';';   } return $res; }}//HTTP Request object class Sinhttprequest {public $url;//Request address public $method = ' GET ';//request method public $host;//Host PU Blic $path; Path public $scheme; Protocol, HTTP public $port; Port public $header; Request header public $body;     Request Body//Set Header function SetHeader ($k, $v) {if (!isset ($this->header)) {$this->header = array ();   } $this->header[$k] = $v;     }//Get request string//Include header and request body//Get write directly after socket on line function reqstring () {$matches = Parse_url ($this->url);     !isset ($matches [' Host ']) && $matches [' host '] = ';     !isset ($matches [' path ']) && $matches [' path '] = '; !isset ($matches [' query ']) && $matches [' query '] = ';     !isset ($matches [' Port ']) && $matches [' port '] = ';     $host = $matches [' Host ']; $path = $matches [' Path ']? $matches [' Path ']. ($matches [' query ']? '?' .     $matches [' query ']: '): '/'; $port =!empty ($matches [' Port '])?     $matches [' Port ']: 80; $scheme = $matches [' scheme ']?     $matches [' scheme ']: ' http ';     $this->host = $host;     $this->path = $path;     $this->scheme = $scheme;     $this->port = $port;     $method = Strtoupper ($this->method);     $res = "$method $path http/1.1\r\n";     $res. = "Host: $host \ r \ n";       if ($this->header) {reset ($this->header); while (list ($k, $v) = each ($this->header)) {if (Isset ($v) && strlen ($v) > 0) $res. = "$       K: $v \ r \ n ";     }} $res. = "\ r \ n";       if ($this->body) {$res. = $this->body;     $res. = "\r\n\r\n";   } return $res; }}//HTTP response class Sinhttpresponse {public $scheme;//protocol  Public $stasus; Status, the success of the time is OK public $code; Status code, the success of the time is the public $header; Response Head public $body;     Response body Function __construct () {$this->header = array ();   $this->body = null;   } function SetHeader ($key, $val) {$this->header[$key] = $val; }}//HttpClient class Sinhttpclient {public $keepcontext = true;//whether the session public $context is maintained;//Context Public $reques T Request public $response;  Response public $debug = false;     Whether the request content and the same head function __construct () {$this->request = new Sinhttprequest () are printed in debug mode,//true;     $this->response = new Sinhttpresponse ();     $this->context = new Sinhttpcontext (); $this->timeout = 15;     The default timeout is 15s}//clears the last Request content function clearrequest () {$this->request->body = ';     $this->request->setheader (' Content-length ', false);   $this->request->setheader (' Content-type ', false); }//Post method//data for the request//for key-value pairs when the simulation form is submitted//other time for data submission, submitted in the form of XML//if there isFor other requirements, please expand function post ($url, $data = False) {$this->clearrequest ();         if ($data) {if (Is_array ($data)) {$con = Http_build_query ($data);       $this->request->setheader (' Content-type ', ' application/x-www-form-urlencoded ');         } else {$con = $data;       $this->request->setheader (' Content-type ', ' text/xml; Charset=utf-8 ');       } $this->request->body = $con;       $this->request->method = "POST";     $this->request->setheader (' Content-length ', strlen ($con));   } $this->startrequest ($url);     }//Get Method function Get ($url) {$this->clearrequest ();     $this->request->method = "GET";   $this->startrequest ($url);     }//The method is called internally, without calling function Startrequest ($url) {$this->request->url = $url; if ($this->keepcontext) {//If the context is saved $this->request->setheader (' Referer ', $this->context-&       Gt;refrer); $cks = $this->context->Cookiesstring ();     if (strlen ($cks) > 0) $this->request->setheader (' Cookie ', $cks);     }//Get request Content $reqstring = $this->request->reqstring ();     if ($this->debug) echo "request:\n$reqstring\n";     try {$fp = Fsockopen ($this->request->host, $this->request->port, $errno, $errstr, $this->timeout);       } catch (Exception $ex) {echo $ex->getmessage ();     Exit (0);       } if ($fp) {stream_set_blocking ($fp, true);       Stream_set_timeout ($fp, $this->timeout);       Write Data fwrite ($FP, $reqstring);       $status = Stream_get_meta_data ($FP);           if (! $status [' timed_out ']) {//Not timed out///The following loop is used to read the response header while (!feof ($fp)) {$h = Fgets ($FP);           if ($this->debug) echo $h;           if ($h && ($h = = "\ n" | | $h = = "\ n")) break;           $pos = Strpos ($h, ': '); if ($pos) {$k = Strtolower (Trim (substr ($h, 0, $pos));             $v = Trim (substr ($h, $pos + 1)); if ($k = = ' Set-cookie ') {//Update cookie if ($this->keepcontext) {$this->c               Ontext->addcookie (New Sincookie ($v));             }} else {//Add head inside to $this->response->setheader ($k, $v);             }} else {//first row of data//parse response status $preg = '/^ (\s*) (\s*) (. *) $/';             Preg_match_all ($preg, $h, $arr);             Isset ($arr [1][0]) & $this->response->scheme = Trim ($arr [1][0]);             Isset ($arr [2][0]) & $this->response->stasus = Trim ($arr [2][0]);           Isset ($arr [3][0]) & $this->response->code = Trim ($arr [3][0]);         }}//Gets the response body length $len = (int) $this->response->header[' content-length ');         $res = "; The following loop reads the body while (!feof ($fp) && $len > 0) {$c = Fread ($fp, $len);          $res. = $c;         $len-= strlen ($c);       } $this->response->body = $res;       }//Close socket fclose ($FP);     Save the return to the context maintenance $this->context->refrer = $url; }}}//demo//Now let begin test it $client = new sinhttpclient ();  Create a client $client->get (' http://www.baidu.com/'); Get Echo $client->response->body; Echo?>

I hope this article is helpful to everyone's PHP programming.

http://www.bkjia.com/PHPjc/1018531.html www.bkjia.com true http://www.bkjia.com/PHPjc/1018531.html techarticle PHP encapsulated HttpClient class usages, encapsulated httpclient This article describes the HttpClient class of PHP encapsulation. Share to everyone for your reference. The specific analysis is as follows: This is a PHP package ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.