Example of PHP-encapsulated HttpClient class usage

Source: Internet
Author: User

Example of PHP-encapsulated HttpClient class usage

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.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

<? Php

/*

* Filename: httpclient. php

* Created on 2012-12-21

* Created by RobinTang

* To change the template for this generated file go

* 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 from the Cookie string

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; // address of the previous page

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;

}

// Obtain the cookie string, which is used in the request

Function cookiesString (){

$ Res = '';

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

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

// Write the socket directly after obtaining it.

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. It is OK when the request is successful.

Public $ code; // status code. The value is 200 when the request is successful.

Public $ header; // 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 {

Public $ keepcontext = true; // whether to maintain the session

Public $ context; // context

Public $ request; // request

Public $ response; // response

Public $ debug = false;

// Whether it is in Debug mode,

// If it is true, the request content and the same header are printed.

Function _ construct (){

$ This-> request = new SinHttpRequest ();

$ 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 ('content-length', false );

$ This-> request-> setHeader ('content-type', false );

}

// Post method

// Data is the requested data

// Simulate form submission when it is a key-Value Pair

// Submit data at other times in the form of xml

// If you have other requirements, expand them by yourself

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 );

}

// This method is an internal call method and does not need to be called directly.

Function startRequest ($ url ){

$ This-> request-> url = $ url;

If ($ this-> keepcontext ){

// Set relevant information if the context is saved

$ This-> request-> setHeader ('Referer', $ this-> context-> refrer );

$ Cks = $ this-> context-> cookiesString ();

If (strlen ($ cks)> 0)

$ This-> request-> setHeader ('cooker', $ cks );

}

// Obtain 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-cookies '){

// Update Cookie

If ($ this-> keepcontext ){

$ This-> context-> addCookie (new SinCookie ($ v ));

}

} Else {

// Add to the header

$ This-> response-> setHeader ($ k, $ v );

}

} Else {

// The first row of data

// Parse the 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]);

}

}

// Obtain the response body length

$ Len = (int) $ this-> response-> header ['content-length'];

$ Res = '';

// Read the body cyclically below

While (! Feof ($ fp) & $ len> 0 ){

$ C = fread ($ fp, $ len );

$ Res. = $ c;

$ Len-= strlen ($ c );

}

$ This-> response-> body = $ res;

}

// Close the 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.

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.