pycURl是python编写的ibcurl.的接口,今天在使用的时候,出现了一个小问题,我发送的数据对方无法正常接收,后来才知道是content-type设置不正确的原因.
pyCURL默认的Content-Type是application/x-www-form-urlencoded,也就是说,如果没有明确设定,则发送的数据是url编码之后的数据.
可是如果用这个工具发送json字符串 的request body,则必须显式指定json对应的内容类型Content-Type:application/json;charset=xxxx,否则接收方收到的数据是错误的.
以下是我写的一个简易curl,具有基本的获取响应数据,和上传文件,携带cookie,保存cookie等功能.
import os
import pycurl
import urllib
from StringIO import StringIO
'''url:请求的urlcookies:携带的cookieposdata:请求体,可以是字符串,或者其他可以urlencode的类型uploadfiles:上传文件的参数,格式为{'name':filename,'path':filepath}referer:来源httpheader:自定义header头ua:客户端代理名cookiejar:存储请求响应后的cookie的文件路径customrequest:自定义请求方法注意:1.暂时没有进行ssl验证2.由于后续需要对请求获取各种数据,比如HTTP_CODE,所以请求发出后并没有关闭,而是将pycurl.Curl对象返回方便查询'''def myCurl(url,cookies='',postdata='',uploadfiles='',referer='',httpheader='',ua='',cookiejar='',customrequest=''): ? ?buffer = StringIO() ? ?c = pycurl.Curl() ? ?c.setopt(c.WRITEDATA, buffer) ? ?c.setopt(pycurl.SSL_VERIFYPEER, 0) ? ?c.setopt(pycurl.SSL_VERIFYPEER, 0) ? ?c.setopt(pycurl.SSL_VERIFYHOST, 0) ? ?c.setopt(pycurl.FOLLOWLOCATION, 1) ? ?if(ua == ''): ? ? ? ?c.setopt(pycurl.USERAGENT,'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36') ? ?else: ? ? ? ?c.setopt(pycurl.USERAGENT,ua) ? ?if(httpheader): ? ? ? ?c.setopt(pycurl.HTTPHEADER,httpheader) ? ?if(referer): ? ? ? ?c.setopt(pycurl.REFERER, referer) ? ?if(cookies): ? ? ? ?c.setopt(pycurl.COOKIE,cookies) ? ?c.setopt(pycurl.URL,url) ? ?if(customrequest): ? ? ? ?c.setopt(pycurl.CUSTOMREQUEST, customrequest) ? ?if(postdata): ? ? ? ?if isinstance(postdata,str):#字符串不要使用urlencode postfields=postdata ? ? ? ?else: ? ? ? ? ? ?postfields=urllib.urlencode(postdata) ? ? ? ?c.setopt(c.POSTFIELDS, postfields) ? ?if(uploadfiles):#如果需要上传文件 multipartFormData=[] ? ? ? ?fileTuple=(uploadfiles['name'], ( ? ? ? ? ? ? ? ?# upload the contents of this file c.FORM_FILE, uploadfiles['path'], ? ? ? ? ? ?)) ? ? ? ?multipartFormData.append(fileTuple) ? ? ? ?if (postdata): #除了文件还要上传其他一些数据,也要加上 for index in postdata: ? ? ? ? ? ? ? ?if(isinstance(postdata[index],int)): ? ? ? ? ? ? ? ? ? ?postdata[index]=str(postdata[index]) ? ? ? ? ? ? ? ?multipartFormData.append((index,postdata[index])) ? ? ? ?c.setopt(c.HTTPPOST, multipartFormData) ? ?if cookiejar: ? ? ? ?c.setopt(pycurl.COOKIEJAR, cookiejar) ? ?res=c.perform() ? ?if cookiejar: ? ? ? ?cookieStr = '' for line in open(cookiejar): ? ? ? ? ? ?if (line.find('#') == 0 or line == '\n'): # 注意换行并不是空字符串,也要去掉 continue ? ? ? ? ? ?line = line.strip('\n') # 去掉空字符串 lineArr = line.split('\t') # 根据制表符切开 length = len(lineArr) ? ? ? ? ? ?name = lineArr[length - 2] ? ? ? ? ? ?value = lineArr[length - 1] ? ? ? ? ? ?cookieStr = cookieStr + name + '=' + value + '; ' ? ? ? ?cookieStr.strip('; ') ? ? ? ?os.remove(cookiejar) ? ?if cookiejar: ? ? ? ?data = {'c': c, 'data': buffer.getvalue(),'cookies':cookieStr} ? ?else: ? ? ? ?data = {'c': c, 'data': buffer.getvalue()} ? ?#c.close() # getinfo must be called before close. return data