The difference of module Urllib,urllib2,httplib
Httplib implements the HTTP and HTTPS client protocols, but in Python, modules Urllib and URLLIB2 have a higher layer of encapsulation for httplib.
Describes the functions used in the following example:
1. httpconnection function
Httplib. Httpconnection (Host[,port[,stict[,timeout]])
This is a constructor that represents an interaction with the server at a time, that is, the request/response
Host identifies the server host (server IP or domain name)
Port defaults are 80
The strict mode is false, indicating that the state row returned by the server cannot be resolved, and whether the Badstatusline exception is thrown
For example:
conn = Httplib. Httpconnection ("192.168.81.16", 80) establishes a link with the server.
2, Httpconnection.request (Method,url[,body[,header]]) function
This is to send a request to the server
method is requested, usually by post or get,
For example:
Method= "POST" or method= "get"
URL requested resource, requested resource (page or CGI, we have CGI here)
For example:
Url= "http://192.168.81.16/cgi-bin/python_test/test.py" request CGI
Or:
Url= "http://192.168.81.16/python_test/test.html" Request page
The body needs to submit data to the server, either in JSON or in the format above, JSON needs to call the JSON module
Headers requested HTTP Header headerdata = {"Host": "192.168.81.16"}
For example:
Test_data = {' Servicecode ': ' AAAA ', ' B ': ' BBBBB '}
Test_data_urlencode = Urllib.urlencode (test_data)
Requrl = "http://192.168.81.16/cgi-bin/python_test/test.py"
Headerdata = {"Host": "192.168.81.16"}
conn = Httplib. Httpconnection ("192.168.81.16", 80)
Conn.request (method= "POST", url=requrl,body=test_data_urlencode,headers = Headerdata)
Conn after use, should be closed, conn.close ()
3, Httpconnection.getresponse () function
This is to get the HTTP response, and the returned object is an instance of HttpResponse.
4, HttpResponse Introduction:
The HttpResponse properties are as follows:
Read ([Amt]) Gets the response message body, which reads the specified byte of data from the response stream and reads all the data when unspecified;
GetHeader (Name[,default]) Gets the response Header,name is the header domain name, and in the absence of a header domain name, default is used to specify the return value
Getheaders () to get header in the form of a list
For example:
Date=response.getheader (' Date ');
Print Date
Resheader= "
Resheader=response.getheaders ();
Print Resheader
Response header information in column form:
[(' Content-length ', ' 295 '), (' accept-ranges ', ' bytes '), (' Server ', ' Apache '), (' last-modified ', ' Sat, Mar 2012 10:07:0 2 GMT '), (' Connection ', ' close '), (' ETag ', ' "E8744-127-4bc871e4fdd80"), (' Date ', ' Mon, Sep 10:01:47 GMT '), (' Cont Ent-type ', ' text/html ')]
Date=response.getheader (' Date ');
Print Date
Remove the value of date from the response header.