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

Source: Internet
Author: User
This article mainly introduces how python sends http requests and receives http responses through get and post. it involves the skills related to using the urllib module and urllib2 module to send data through get and post, for more information about how to send http requests and receive http responses through get and post in python, see the following example. 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:

#!/usr/bin/pythonimport cgidef main():   print "Content-type: text/html\n"  form = cgi.FieldStorage()  if form.has_key("ServiceCode") and form["ServiceCode"].value != "":    print " Hello",form["ServiceCode"].value,""   else:      print " Error! Please enter first name." 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,

import urllibimport urllib2url = "http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa"req = urllib2.Request(url)print reqres_data = urllib2.urlopen(req)res = res_data.read()print res

Method 2,

import httpliburl = "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,

import urllibimport urllib2test_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 reqres_data = urllib2.urlopen(req)res = res_data.read()print res

Method 2,

import urllibimport 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 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:

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 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:

date=response.getheader('date');print dateresheader=''resheader=response.getheaders();print resheader

Response header in column form:

[('content-length', '295'), ('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.