python不同版本中的urllib的问题!

import base64
import urllib2

class SGovToken():
    TIME_OUT = 3600
    LAST_UPDATE_TIME = ""
    TOKEN = ''

    def __init__(self, *args, **kwargs):
        pass

    def get_token_from_sgovernace(self,appid,appkey,url):
        if not appid or not appkey:
            return 'ERROE'
        
        soap_env = '''
                    <applicationID>{0}</applicationID>
                    <credential>{1}</credential>
                    '''
        appkey = base64.standard_b64decode(appkey)
        soap_content = soap_env.format(appid,appkey)
        resquest = urllib2.Request(url,soap_content)
        resquest.add_header('SOPAACTION','getTokenByAPPCREdential')

        try:
            response = urllib2.urlopen(resquest)
        except HTTPERROR as e:
            pass
        if response is not none:
            resp_content = response.read()
            return resp_content

现在的代码在python2中可以正常的获取到resp_content....但是在python3中,将urllib2改为urllib.request却是报错的。urllib2.Request的data参数也改为了bytes类型!!!不知道哪里还有问题呢?

阅读 2.3k
1 个回答

建议你用个 IDE, 如 PyCharm CE 版本的, 开源免费. 不要在这低级问题上浪费自己宝贵的时间.
你这个代码放到IDE, 所有错误一览无余.

或使用代码升级工具, 如 http://pythonconverter.com/
https://docs.python.org/2/lib...

使用

$ 2to3 -w urltest.py

可以得到:

import base64
import urllib.request, urllib.error, urllib.parse


class SGovToken():
    TIME_OUT = 3600
    LAST_UPDATE_TIME = ""
    TOKEN = ''

    def __init__(self, *args, **kwargs):
        pass

    def get_token_from_sgovernace(self, appid, appkey, url):
        if not appid or not appkey:
            return 'ERROE'

        soap_env = '''
                    <applicationID>{0}</applicationID>
                    <credential>{1}</credential>
                    '''
        appkey = base64.standard_b64decode(appkey)
        soap_content = soap_env.format(appid, appkey)
        resquest = urllib.request.Request(url, soap_content)
        resquest.add_header('SOPAACTION', 'getTokenByAPPCREdential')

        try:
            response = urllib.request.urlopen(resquest)
        except urllib.error.HTTPERROR as e:
            pass
        if response is not None:
            resp_content = response.read()
            return resp_content

是不是很轻松呢

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题