Python uses get and post methods to send http requests and receive http responses

Source: Internet
Author: User

Python uses get and post methods to send http requests and receive http responses

This example describes how python sends http requests and receives http responses through get and post. Share it with you for your reference. The details are as follows:

CGI is used for testing. It is named test. py and stored in the cgi-bin directory of apache:

?

1

2

3

4

5

6

7

8

9

10

#! /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 the get method is used, the request data is directly placed in the url.

Method 1,

?

1

2

3

4

5

6

7

8

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 2,

?

1

2

3

4

5

6

7

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 the post method is used, the data is placed in data or body, and cannot be placed in the url. The data is ignored in the url.

Method 1,

?

1

2

3

4

5

6

7

8

9

10

Import urllib

Import urllib2

Test_data = {'servicecode': 'aaa', '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 2,

?

1

2

3

4

5

6

7

8

9

10

11

Import urllib

Import httplib

Test_data = {'servicecode': 'aaa', '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 usage of json in python is unclear, so the urllib. urlencode (test_data) method is used temporarily;

Differences between modules urllib, urllib2, and httplib

Httplib implements http and https client protocols, but in python, the modules urllib and urllib2 encapsulate httplib in a higher layer.

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, that is, a request/response.

Host identifies the server host (Server IP address or domain name)

The default port value is 80.

The strict mode is False, indicating whether to throw a BadStatusLine exception when the status row returned by the server cannot be parsed.

For example:

Conn = httplib. HTTPConnection ("192.168.81.16", 80.

2. HTTPConnection. request (method, url [, body [, header]) Function

This is a request sent to the server.

Method Request method, usually post or get,

For example:

Method = "POST" or method = "Get"

Url requested resource, requested resource (page or CGI, here we are CGI)

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 must be submitted to the server. json can be used or in the preceding format. json needs to call the json module.

Headers request http header headerdata = {"Host": "192.168.81.16 "}

For example:

?

1

2

3

4

5

6

Test_data = {'servicecode': 'aaa', '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 should be closed after use, conn. close ()

3. HTTPConnection. getresponse () function

This is an http response. The returned object is an instance of HTTPResponse.

4. HTTPResponse introduction:

The attributes of HTTPResponse are as follows:

Read ([amt]) gets the Response Message Body. amt indicates reading data of the specified byte from the response stream. If not specified, all data is read;

Getheader (name [, default]) obtains the response header. name indicates the header domain name. When no header domain name exists, default specifies the return value.

Getheaders () obtains the header in the form of a list.

For example:

?

1

2

3

4

5

Date = response. getheader ('date ');

Print date

Resheader =''

Resheader = response. getheaders ();

Print resheader

Response Header in column form:

?

1

2

3

[('Content-length', '20140901'), ('Accept-ranges', 'bytes '), ('server', 'apache '), ('Last-modified', 'sat, 31 Mar 2012 10:07:02 gmt'), ('connection', 'close'), ('etag', '"e8744-127-4bc871e4fdd80 "'), ('date', 'mon, 03 Sep 2012 10:01:47 gmt'), ('content-type', 'text/html')]

Date = response. getheader ('date ');

Print date

Obtain the date value of the response header.

I hope this article will help you with Python 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.