PyCurl上传文件客户端

PyCurl上传文件

#!/usr/bin/env python
#
-*- coding: utf-8 -*-
import pycurl
import StringIO

c = pycurl.Curl() #创建一个同libcurl中的CURL处理器相对应的Curl对象
fp = StringIO.StringIO()
c.setopt(pycurl.WRITEFUNCTION, fp.write)
c.setopt(pycurl.FOLLOWLOCATION, 1)
c.setopt(pycurl.MAXREDIRS, 5)
c.setopt(pycurl.CONNECTTIMEOUT, 60)
c.setopt(pycurl.TIMEOUT, 300)
c.setopt(c.POST, 1)

c.setopt(c.URL, "http://localhost:8080/upload.action") #设置要访问的网址
#
设置post请求, 上传文件的字段名 上传的文件
c.setopt(c.HTTPPOST, [("theFile", (c.FORM_FILE, "/home/ubuntu/avatar.jpg"))])
c.perform() #执行上述访问网址的操作
c.close() #Curl对象无操作时,也会自动执行close操作
print "the python shell over!"

PyCurl POST请求

#!/usr/bin/env python
#
-*- coding: utf-8 -*-
import pycurl
import StringIO

post_data_dic = {"md5":md5, "desc":"the file md5"}
c = pycurl.Curl() #创建一个同libcurl中的CURL处理器相对应的Curl对象
fp = StringIO.StringIO()
c.setopt(pycurl.WRITEFUNCTION, fp.write)
c.setopt(pycurl.FOLLOWLOCATION, 1)
c.setopt(pycurl.MAXREDIRS, 5)
c.setopt(pycurl.CONNECTTIMEOUT, 60)
c.setopt(pycurl.TIMEOUT, 300)
c.setopt(c.POST, 1)

c.setopt(c.URL, "http://localhost:8080/post.action") #设置要访问的网址
c.setopt(c.POSTFIELDS, urllib.urlencode(post_data_dic))
c.perform() #执行上述访问网址的操作
c.close() #Curl对象无操作时,也会自动执行close操作
print "the python shell over!"

你可能感兴趣的:(curl)