Example of PHP-encapsulated HttpClient class usage

Source: Internet
Author: User
This article mainly introduces the PHP-encapsulated HttpClient class, which can implement simple GET, POST, Cookie, Session, and other functions. For more information, see

This article mainly introduces the PHP-encapsulated HttpClient class, which can implement simple GET, POST, Cookie, Session, and other functions. For more information, see

This example describes the HttpClient class encapsulated by PHP. Share it with you for your reference. The specific analysis is as follows:

This is a php-encapsulated HttpClient class that can implement simple functions such as get post Cookie Session. I have done it before. I modified it again in the past two days.

<? Php/** Filename: httpclient. php * Created on 2012-12-21 * Created by RobinTang * To change the template for this generated file go to * Window-Preferences-PHPeclipse-PHP-Code Templates */class SinCookie {public $ name; // Cookie name public $ value; // Cookie value // The following three attributes are not implemented now public $ expires; // expiration time public $ path; // path public $ domain; // domain // create a Cookie object function _ construct ($ s = false) from the Cookie string ){ If ($ s) {$ i1 = strpos ($ s, '='); $ i2 = strpos ($ s ,';'); $ this-> name = trim (substr ($ s, 0, $ i1); $ this-> value = trim (substr ($ s, $ i1 + 1, $ i2-$ i1-1) ;}// obtain the Cookie key value pair function getKeyValue () {return "$ this-> name = $ this-> value" ;}// session context class SinHttpContext {public $ cookies; // session Cookiespublic $ referer; // function _ construct () {$ this-> cookies = array (); $ this-> refrer = "" ;}// set Cookiefunction Cookie ($ key, $ val) {$ ck = new SinCookie (); $ ck-> name = $ key; $ ck-> value = $ val; $ this-> addCookie ($ ck);} // Add Cookiefunction addCookie ($ ck) {$ this-> cookies [$ ck-> name] = $ ck ;} // obtain the cookie string. function cookiesString () {$ res = ''; foreach ($ this-> Cookies as $ ck) {$ res is used in the request. = $ ck-> getKeyValue (). ';} return $ res ;}// class SinHttpRequest {public $ url of the Http request object; // public $ method = 'get'; // public of the request method $ Host; // host public $ path; // path public $ scheme; // protocol, httppublic $ port; // port public $ header; // Request header public $ body; // Request body // set the header function setHeader ($ k, $ v) {if (! Isset ($ this-> header) {$ this-> header = array () ;}$ this-> header [$ k] = $ v ;} // obtain the request string // contains the header and request body // after obtaining the string, write the socket directly to 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']: ''):' http://www.jb51.net/ '; $ 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";} return $ res ;}// Http response class SinHttpResponse {public $ scheme; // protocol public $ stasus; // status. The status code is okpublic $ code when the request succeeds. // the status code is 200 public $ header when the request succeeds. // The response header is 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 to maintain Session public $ context; // context public $ request; // request public $ response; // response public $ debug = false; // whether the Debug mode is enabled, // if it is true, the request content and the same header function _ construct () {$ this-> request = new SinHttpRequest () will be printed (); $ this-> response = new SinHttpResponse (); $ this-> context = new SinHttpContext (); $ this-> timeout = 15; // The default timeout value is 15 s} // clear the last request content function clearRequest () {$ this-> request-> body = ''; $ this-> request-> setHeader ('Con Tent-length', false); $ this-> request-> setHeader ('content-type', false );} // post method // data is the requested data // simulate form submission when the key-value pair is used // submit data at other times, the submission form is xml // if you have 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 ('cont Ent-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);} // this method is an internal call method, you do not need to directly call function startRequest ($ url) {$ this-> request-> url = $ url; if ($ this-> keepcontext) {// if If the context is saved, set the relevant information $ this-> request-> setHeader ('Referer', $ this-> context-> refrer ); $ cks = $ this-> context-> cookiesString (); if (strlen ($ cks)> 0) $ this-> request-> setHeader ('cookie ', $ cks);} // get the 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']) {// No timeout // The following loop is used to read the Response Header while (! Feof ($ fp) {$ h = fgets ($ fp); if ($ this-> debug) echo $ h; if ($ h & ($ h = "\ r \ 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-cookier ') {// update Cookieif ($ this-> keepcontext) {$ this-> context-> addCookie (new SinCookie ($ v ));}} else {// Add to the header $ this-> response-> setHeader ($ k, $ v );}} else {// The first row of Data // resolution response status $ preg =' /^ (\ 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]) ;}// get 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 Socketfclose ($ fp ); // Save the returned result to 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 will help you with php programming.

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.