Example of HttpClient class usage encapsulated by PHP, encapsulation of httpclient_PHP tutorial

Source: Internet
Author: User
Tags preg set cookie
Example of HttpClient class usage encapsulated by PHP, and httpclient. PHP-encapsulated HttpClient class usage example. httpclient this article describes the PHP-encapsulated HttpClient class. Share it with you for your reference. The specific analysis is as follows: this is an example of HttpClient class usage encapsulated by php and httpclient

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) {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 Cookies public $ referer; // 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;} // you can call function cookiesString () {$ res = ''to obtain Cookies ''; foreach ($ this-> cookies as $ ck) {$ res. = $ ck-> getKeyValue (). ';} return $ res ;}// class SinHttpRequest {public $ url of the Http request object; // Request address public $ method = 'get'; // request method public $ host; // host public $ path; // path public $ scheme; // protocol, http public $ 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']: ''):'/'; $ 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. when the request is successful, the value is OK public $ code; // status code. when the request is successful, the value is 200 public $ header; // The response header public $ body; // response body function _ construct () {$ this-> header = array (); $ this-> body = null;} function setHeader ($ key, $ val) {$ this-> header [$ key] = $ val ;}// HttpClient class SinHttpClient {p Ublic $ keepcontext = true; // whether to maintain the session public $ context; // The context public $ request; // The request public $ response; // The response public $ debug = false; // whether it is in Debug mode. // 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-> re Quest-> body = ''; $ this-> request-> setHeader ('content-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-urle Ncoded ');} 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);} // this method is an internal call method and does not need to be called directly StartRequest ($ url) {$ this-> request-> url = $ url; if ($ this-> keepcontext) {// 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-> reques T-> 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 Cookie if ($ this-> keepcontext) {$ this-> context-> addCookie (new SinCookie ($ v ));}} else {// add to the header $ this-> response-> setHeader ($ k, $ v) ;}} else {// The first line 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 Socket fclose ($ 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.

Examples in this article describes the HttpClient class encapsulated by PHP. Share it with you for your reference. The specific analysis is as follows: this is a php encapsulation...

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.