python发送http请求

来源:互联网 发布:苹果6的4g网络慢怎么办 编辑:程序博客网 时间:2024/05/17 06:26
import httplib,urllibfrom urlparse import urlparseclass NetUtil:    errcode=''    errmsg=''    def http_get(self,url,timeout=5,is_https=False):        domain=query_str=data=''        o=urlparse(url)        domain=o.netloc        if ''!=o.path or ''!=o.query:            query_str=o.path+'?'+o.query        if is_https:            conn=httplib.HTTPSConnection(domain,443,timeout)        else:            conn=httplib.HTTPConnection(domain,80,timeout)        conn.request('GET',query_str)        resp=conn.getresponse()        status=resp.status        if 200==status:            data=resp.read()        else:            self.errcode=''            self.errmsg='http response code(%s):%s' % (status,resp.reason)                    conn.close()        return data        def http_post(self,url,ps={},timeout=5,is_https=False):        headers={"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}        domain=query_str=data=''        o=urlparse(url)        domain=o.netloc        if ''!=o.path or ''!=o.query:            query_str=o.path+'?'+o.query        if is_https:            conn=httplib.HTTPSConnection(domain,443,timeout)        else:            conn=httplib.HTTPConnection(domain,80,timeout)                        ps=urllib.urlencode(ps)        conn.request('POST',query_str,ps,headers)        resp=conn.getresponse()        status=resp.status        if 200==status:            data=resp.read()        else:            self.errcode=''            self.errmsg='http response code(%s):%s' % (status,resp.reason)                    conn.close()        return data
#http请求okcoin接口获取LTC最新价格行情
url='https://www.okcoin.com/api/ticker.do?symbol=ltc_cny'm=NetUtil()resp=m.http_get(url)if ''==resp:    print m.errcode,m.errmsgelse:    print resp

0 0
原创粉丝点击