python urllib2实现http GET PUT DELETE POST的方法

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/3/11 下午8:33
# @Author  : lb
# @File    : httpMethod.py 定义了http 常用的请求

import urllib2
import urllib
import socket
import json



class httpMethod(object):

    def __init__(self):
        pass

    def post(self, url=None, params=None, timeout=50):
        """Post方法"""
        old_timeout = socket.getdefaulttimeout()
        socket.setdefaulttimeout(timeout)
        try:
            # POST
            if params:
                request = urllib2.Request(url, urllib.urlencode(params))
            # GET
            else:
                request = urllib2.Request(url)
            request.add_header('Accept-Language', 'zh-cn')
            response = urllib2.urlopen(request)
            content = response.read()
            if response.code == 200:
                return content, True
            return content, False
        except Exception as ex:
            print ("Post 方法调用异常:%s" % ex)
            return str(ex), False
        finally:
            if 'response' in dir():
                response.close()
            socket.setdefaulttimeout(old_timeout)

    def put(self, url=None, params=None, urlencode=True):
        """urlencode 表明参数是否需要被编码,如果此选项为false。传入的params 需要是字符串形式"""
        try:
            if urlencode:
                data = urllib.urlencode(params)
            else:
                data = params
            req = urllib2.Request(url, data)
            req.get_method = lambda: 'PUT'
            ret = urllib2.urlopen(req).read()
            return ret
        except Exception as ex:
            print("PUT 方法调用异常:%s" % ex)
           

    def get(self, url):
        """get方法"""
        try:
            req = urllib2.Request(url)
            ret = urllib2.urlopen(req)
            return json.load(ret)
        except Exception as ex:
            print("Get方法调用异常:%s" % ex)
           

    def http_del(self, url=None, params=None):
        """定义delete 方法"""
        try:
            data = urllib.urlencode(params)
            req = urllib2.Request(url, data)
            req.get_method = lambda: 'DELETE'
            ret = urllib2.urlopen(req).read()
            return ret
        except Exception as ex:
            print("DELETE 方法调用异常:%s" % ex)
           

  

posted on 2019-03-16 21:19  我是某某某是我  阅读(473)  评论(0编辑  收藏  举报

导航