Analysis of post and get differences in HTTP and simulation of their responses and requests using Python

Source: Internet
Author: User
Tags http post

Recently in a few weeks do hand-travel crash information collection and upload, get crash information, using the HTTP POST method to upload to the company's common server, so do a simple summary. This article first introduces the HTTP protocol, mainly explains the difference between the post method and the Get method, then implements the response to the Post method and the Get method with Python, and finally simulates the request of the Post method and the Get method with Python.

Introduction to the HTTP protocol

HTTP is an abbreviation for the Hyper Text Transfer Protocol (Hypertext Transfer Protocol), which is simply an application-level protocol that allows Hypertext Markup Language (HTML) documents to be routed from the Web server to the client's browser. HTTP is a stateless protocol, that is, the same client's request and the last request is not the corresponding relationship, for the HTTP server, it does not know that the two requests from the same client, in order to solve this problem, the Web application introduced a cookie mechanism to maintain state.
The HTTP protocol is usually implemented based on the TCP protocol, sometimes based on the TLS or SSL protocol (the two Protocol is also implemented based on the TCP protocol), which is what we often call HTTPS, Each HTTP operation has at least one of the following procedures: First, the client establishes a connection with the server, and when established, the client sends the request in the protocol format, and after the service has received the request, it returns the response data in a format, and the client disconnects from the server.
Usually we open a Web page, we need the browser to send multiple requests, because a Web page may refer to other files, compared to files, this time the browser will automatically send the request again to get pictures and other data, until the data on the page is fully displayed.

Post and get differences

The HTTP protocol defines a number of ways to interact with the server, the most basic of which are 4, get,post,put,delete, respectively. A URL address is used to describe a resource on a network, while the Get, POST, PUT, delete in HTTP corresponds to the search for this resource, change, add, delete 4 operations, the most common request method is get and post, and now the browser generally only support the get and post methods. Get is generally used to get/query resource information, while post is typically used to update resource information, the main differences between them are as follows:
1) According to the HTTP specification, get is used for information acquisition, and should be secure and idempotent, where security means that the operation is used to obtain information rather than modify information, idempotent means that multiple requests to the same URL should return the same result (which may not be satisfied in the actual implementation);
Post represents a request that may modify resources on the server.
2) The data of the GET request is appended to the URL (that is, the data is placed in the HTTP protocol header), to split the URL and transfer data, the parameters are connected to &, if the data is English letter/number, as is sent, if it is a space, converted to +, if it is Chinese/other characters,
The string is directly encoded with BASE64, and the post submits the data to the packet in the HTTP packet.
3) because get is submitted through a URL, the amount of data that can be submitted is directly related to the length of the URL, there is no limit to the length of the URL, that is, the HTTP protocol does not specify the length of the URL, but in essence, a particular browser may limit this length In theory, the post is also no size limit, the HTTP protocol specification is not a size limit, but on the server is usually a limit to this size, of course, this limit is more relaxed than get, that is, the use of Post can submit more data than get.
Finally, some online people say that post security is higher than get security, essentially post and get are plaintext transmission, which can be seen through similar wireshark tools. In summary, get is a request to send data to the server, and post is a request to submit data to the server.

The post and get methods respond to Python implementations

The following code implements the response to the Post method and the Get method:

#!/usr/bin/python#coding=utf8 "" "Import sysreload (SYS) sys.setdefaultencoding (' Utf-8 ')" "" from Basehttpserver Import Basehttprequesthandler,httpserverfrom OS import curdir, sepimport cgiimport loggingimport timeport_number = 8080RES_ File_dir = "." Class MyHandler (Basehttprequesthandler):d ef do_get (self): if self.path== "/": Self.path= "/index_example3.html" try:# Based on the requested file name extension, set the correct MIME type sendReply = Falseif self.path.endswith (". html"): Mimetype= ' text/html ' sendReply = Trueif Self.path.endswith (". jpg"): mimetype= ' image/jpg ' sendReply = Trueif self.path.endswith (". gif"): Mimetype= ' image/ GIF ' sendReply = Trueif self.path.endswith (". js"): mimetype= ' application/javascript ' sendReply = Trueif Self.path.endswith (". css"): mimetype= ' text/css ' sendReply = trueif sendReply = = True: #读取相应的静态资源文件 and send it f = open (CurDir + Sep + self.path, ' RB ') Self.send_response ($) self.send_header (' Content-type ', mimetype) self.end_headers () Self.wfile.write (F.read ()) f.close () returnexcept IOError:self.send_error (404, ' File not Found:%s '% self. Path) def do_post (self): logging.warning (self.headers) Form = cgi. Fieldstorage (fp=self.rfile,headers=self.headers,environ={' request_method ': ' POST ', ' content_type ': self.headers[' Content-type '],}) file_name = Self.get_data_string () path_name = '%s/%s.log '% (res_file_dir,file_name) fwrite = open ( Path_name, ' a ') fwrite.write ("name=%s\n"% form.getvalue ("name", "")) Fwrite.write ("addr=%s\n"% form.getvalue ("addr", "")) Fwrite.close () self.send_response (+) self.end_headers () self.wfile.write ("Thanks for You post") def Get_data_ String (self): now = Time.time () Clock_now = Time.localtime (now) Cur_time = List (clock_now) date_string = "%d-%d-%d-%d-%d-% D "% (Cur_time[0],cur_time[1],cur_time[2],cur_time[3],cur_time[4],cur_time[5]) return date_stringtry:server = Httpserver ((', port_number), MyHandler) print ' Started httpserver on PORT ', Port_numberserver.serve_forever () except Keyboardinterrupt:print ' ^c received, shutting down the Web server ' Server.socket.close ()
For the above post response implementation, it is worth mentioning that if the client sends a file, then the method GetValue () will read the entire file content into memory, which may not be what we want, you can use the form's properties file or filename, such as the following code, To calculate the number of lines to upload code:

Fileitem = form["UserFile"]if fileitem.file:    linecount = 0 while    1: Line        = Fileitem.file.readline ()        if Not line:break        linecount = linecount + 1
the Post and Get methods request Python implementations
The following code implements the request for the Get method:

#!/usr/bin/env Python#coding=utf8 import httplib httpClient = None try:    httpClient = Httplib. Httpconnection (' localhost ', 8080, timeout=30)    httpclient.request (' GET ', '/test0.html ')     # Response is HttpResponse object    response = Httpclient.getresponse ()    print Response.Status    print Response.reason    Print response.read () except Exception, E:    print efinally:    if httpClient:        Httpclient.close ()
The following code implements the request for the Post method:
#!/usr/bin/env Python#coding=utf8 import httplib, Urllib httpClient = nonetry:    params = Urllib.urlencode ({' Name ': ' Maximus ', ' addr ': "GZ"})    headers = {"Content-type": "application/x-www-form-urlencoded"                    , "Accept": "text/ Plain "}     httpClient = Httplib. Httpconnection ("localhost", 8080, timeout=30)    httpclient.request ("POST", "/test0.html", params, headers)     Response = Httpclient.getresponse ()    print response.status    print Response.reason    print response.read ()    print response.getheaders () #获取头信息except Exception, E:    print efinally:    if httpClient:        Httpclient.close ()
References

Http://www.cnblogs.com/TankXiao/archive/2012/02/13/2342672.html
Http://www.cnblogs.com/hyddd/archive/2009/03/31/1426026.html
Http://www.acmesystems.it/python_httpserver
http://georgik.sinusgear.com/2011/01/07/how-to-dump-post-request-with-python/
http://www.01happy.com/python-httplib-get-and-post/

Analysis of post and get differences in HTTP and simulation of their responses and requests using Python

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.