Python sends HTTP requests and receives HTTP responses via get, post-urllib urllib2

Source: Internet
Author: User
Tags urlencode

Python sends HTTP requests and receives HTTP responses via get mode, post -Import urllib module, URLLIB2 module, httplib module

Http://blog.163.com/[email protected]/blog/static/132229655201231085444250/

The test CGI, named test.py, is placed under Apache's Cgi-bin directory:
#!/usr/bin/python
Import CGI
def main ():
Print "Content-type:text/html\n"
form = CGI. Fieldstorage ()
If Form.has_key ("Servicecode") and form["Servicecode"].value! = "":
Print "Else
Print "Main ()

Python sends Post and GET requests

GET Request:

When you use the Get method, the request data is placed directly in the URL.
Method One,
Import Urllib
Import Urllib2

url = "Http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa"

req = Urllib2. Request (URL)
Print Req

Res_data = Urllib2.urlopen (req)
res = Res_data.read ()
Print Res

Method Two,
Import Httplib

url = "Http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa"

conn = Httplib. Httpconnection ("192.168.81.16")
Conn.request (method= "GET", Url=url)

Response = Conn.getresponse ()
res= Response.read ()
Print Res

POST request:

When using the Post method, the data is placed in the database or the body, and cannot be placed in the URL and will be ignored in the URL.
Method One,
Import Urllib
Import Urllib2

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"

req = Urllib2. Request (url = requrl,data =test_data_urlencode)
Print Req

Res_data = Urllib2.urlopen (req)
res = Res_data.read ()
Print Res


Method Two,
Import Urllib
Import Httplib
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")

Conn.request (method= "POST", url=requrl,body=test_data_urlencode,headers = Headerdata)

Response = Conn.getresponse ()

res= Response.read ()

Print Res
The use of JSON in Python is unclear, so the Urllib.urlencode (Test_data) method is used temporarily.

The difference between module Urllib,urllib2,httplib
Httplib implements the client protocol for HTTP and HTTPS, but in Python, the modules Urllib and URLLIB2 have a higher-level encapsulation of httplib.

Describe the functions used in the following example:
1. httpconnection function

Httplib. Httpconnection (Host[,port[,stict[,timeout]])
This is a constructor that represents a single interaction with the server, that is, the request/response
Host identifies server hosts (server IP or domain name)
Port default value is 80
Strict mode is false, indicating that the state row returned by the server cannot be resolved, and if 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 sending a request to the server
Method request, typically a post or get,

For example:

Method= "POST" or method= "Get"
URL request resource, requested resource (page or CGI, we are 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
HTTP header for headers request 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 the get HTTP response, and the returned object is an instance of HttpResponse.


4, HttpResponse Introduction:
The properties of the HttpResponse are as follows:
Read ([Amt]) Gets the body of the response message that the AMT represents reads the specified bytes of data from the response stream, without specifying the entire data;
GetHeader (Name[,default]) received a response header,name is the header domain name, when there is no header domain name, the default is used to specify the return value
Getheaders () Get the 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 the date of the response header.

Python sends HTTP requests and receives HTTP responses via get, post-urllib urllib2

Related Article

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.