How Python sends Form-data requests and stitching form-data content

Source: Internet
Author: User
The online approach to sending Multipart/form-data using Python is mostly based on

Ulrlib2 's analog post method, as follows:

Import urllib2boundary= '-------------------------7df3069603d6 ' data=[] data.append ('--%s '% boundary) data.append (' Content-disposition:form-data; Name= "app_id" \ r \ n ') data.append (' xxxxxx ') data.append ('--%s '% boundary) data.append (' Content-disposition:form-data ; Name= "version" \ r \ n ') data.append (' xxxxx ') data.append ('--%s '% boundary) data.append (' Content-disposition:form-data ; Name= "platform" \ r \ n ') data.append (' xxxxx ') data.append ('--%s '% boundary) data.append (' Content-disposition: Form-data; Name= "Libzip"; Filename= "C:\Users\danwang3\Desktop\libmsc.zip" ') data.append (' content-type:application/octet-stream\r\n ')  Fr=open (' C:\Users\danwang3\Desktop\libmsc.zip ') Content=fr.read () data.append (content) print content Fr.close () Data.append ('--%s--\r\n '%boundary) httpbody= ' \ r \ n '. Join (data)  print type (httpbody) print Httpbody  

After testing, using the above method to send a binary file, the server error, data problems!

The problem is ' \ r \ n '. The code of the join (data), which has binary data inside it, may be a problem by converting the data to the UTF-8 format.

Search for a lot of data, you can use the requests Library to submit Multipart/form-data format

A multipart/form-data form data, caught in HTTP inside the following:

#Content-disposition:form-data;name= "app_id" 123456#-----------------------------7df23df2a0870# Content-disposition:form-data;name= "Version"  2256-----------------------------7df23df2a0870 Content-disposition:form-data; Name= "platform"  iOS-----------------------------7df23df2a0870 content-disposition:form-data;name= "Libzip"; Filename= "C:\Users\danwang3\Desktop\libmsc.zip" content-type:application/x-zip-compressed

<二进制文件数据未显示>

---------------------------7df23df2a0870-


The above data in the requests can be simulated as:

files={' app_id ':(none, ' 123456 '),  ' version ':(none, ' 2256 '),  ' platform ':(none, ' iOS '),  ' libzip ':(' Libmsc.zip ', open (' C:\Users\danwang3\Desktop\libmsc.zip ', ' RB '), ' application/x-zip-compressed ')}

Send the above post request, which is a simple

Response=requests.post (Url,files=files)

It's so simple.

On the official website, requests simulates a form data format as follows:

Files = {' name ': ( ,,, )}

This line simulates the post data as:

Content-disposition:form-data; Name= ' name '; filename=
 
  
   
  content-type: 
  
    
   
    
     
    --boundary
   
    
  
   
 
  

If filename and Content-type are not written, then the data that responds to the analog post will not have both.

Often using requests does not automatically manage cookies as you would with URLLIB2, but if you get a cookie

The cookie can be sent out in a requests request.

The cookie format used by requests is as follows:

newcookie={}newcookie[' key1 ']= ' value1 ' newcookie[' key2]= "value2 ' newcookie[' Key3 ']= ' value3 '


Sending cookies can be used:

Response=requests.post (Url,cookies=newcookie)

That's it.

Stitching Form-data Post Content

#!\urs\bin\env python #encoding: utf-8 #设置编码方式 from HTTP2 import http import urllib def readfileascontent (filename): #print filename Try:with open (filename, ' RB ') as F:filecontent = F.read () except Exception, E:prin T ' the Error Message in Readfileascontent (): ' + e.message return ' return filecontent def get_content_type (file     Name): Import mimetypes return mimetypes.guess_type (filename) [0] or ' application/octet-stream ' def isfiledata (P_STR):   import Re r_c = Re.compile ("^f" (. *) ' $ ") Rert = R_c.search (str (P_STR)) #rert = Re.search (" ^f "(. *) ' $", p_str) If Rert:return rert.group (1) else:return None def encode_multipart_formdata (Fields): "" This function is used for stitching The contents of the body part of the Multipart/form-data type of HTTP request return the header definition "Import random import os boundary = Content-type"     '----------%s '% '. Join (Random.sample (' 0123456789abcdef ')) CRLF = ' \ r \ n ' L = [] for (key, Value) in fields: filepath = Isfiledata (vAlue) If Filepath:l.append ('--' + boundary) l.append (' Content-disposition:form-data; name= '%s '; filename = "%s" '% (key, Os.path.basename (filepath))) L.append (' Content-type:%s '% Get_content_type (filepath)) l.append       ('') L.append (Readfileascontent (filepath)) else:l.append ('--' + boundary ') l.append (' Content-disposition:form -data; Name= "%s" '% key "L.append (") l.append (value) l.append ('---' + boundary + '--') l.append (') BODY = CRL F.join (L) content_type = ' multipart/form-data;  boundary=%s '% boundary return Content_Type, body

It is important to note that the dictionary value of the file data, in the form of f '/path/to/file ', is called as follows:

The returned content is a tuple, the first parameter is the value of Content-type in the request header, and the second is the content of the specific post. Then you can send it using the Post method of Httplib.

  • 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.