zoukankan      html  css  js  c++  java
  • Http client to POST using multipart/formdata

    转载一段python代码,通过urllib2使用multipart/form-data来发送文件

    import httplib, mimetypes
    
    def post_multipart(host, selector, fields, files):
        """
        Post fields and files to an http host as multipart/form-data.
        fields is a sequence of (name, value) elements for regular form fields.
        files is a sequence of (name, filename, value) elements for data to be uploaded as files
        Return the server's response page.
        """
        content_type, body = encode_multipart_formdata(fields, files)
        h = httplib.HTTP(host)
        h.putrequest('POST', selector)
        h.putheader('content-type', content_type)
        h.putheader('content-length', str(len(body)))
        h.endheaders()
        h.send(body)
        errcode, errmsg, headers = h.getreply()
        return h.file.read()
    
    def encode_multipart_formdata(fields, files):
        """
        fields is a sequence of (name, value) elements for regular form fields.
        files is a sequence of (name, filename, value) elements for data to be uploaded as files
        Return (content_type, body) ready for httplib.HTTP instance
        """
        BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
        CRLF = '\r\n'
        L = []
        for (key, value) in fields:
            L.append('--' + BOUNDARY)
            L.append('Content-Disposition: form-data; name="%s"' % key)
            L.append('')
            L.append(value)
        for (key, filename, value) in files:
            L.append('--' + BOUNDARY)
            L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
            L.append('Content-Type: %s' % get_content_type(filename))
            L.append('')
            L.append(value)
        L.append('--' + BOUNDARY + '--')
        L.append('')
        body = CRLF.join(L)
        content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
        return content_type, body
    
    def get_content_type(filename):
        return mimetypes.guess_type(filename)[0] or 'application/octet-stream'

    建议将httplib.HTTP更换为httplib.HTTPConnection,这样一来就能在httplib.Connection初始化的时候传入一个timeout,以实现更灵活的控制。

    参阅:
    http://code.activestate.com/recipes/146306/
    http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2

  • 相关阅读:
    Thinking in Java——笔记(14)
    Thinking in Java——笔记(12)
    frp对http协议应用
    我收藏的连接
    linux下 .netcore 微服务注册到SpringClound
    linux 上使用libxls读和使用xlslib写excel的方法简介
    window下 ANSI Unicode utf8之间相互转换
    提取CString中的汉字及个数
    MFC通过sql访问excel的方法
    linux上安装mysql及简单的使用
  • 原文地址:https://www.cnblogs.com/Jerryshome/p/2836112.html
Copyright © 2011-2022 走看看