Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用pycurl将url请求转换为python请求?_Python_Python Requests_Pycurl - Fatal编程技术网

如何使用pycurl将url请求转换为python请求?

如何使用pycurl将url请求转换为python请求?,python,python-requests,pycurl,Python,Python Requests,Pycurl,我想修改以下代码以运行“使用请求”模块。 我在网站上有以下代码: def post(url, message, key, sign): curl = pycurl.Curl() curl.setopt(pycurl.URL, url) curl.setopt(pycurl.SSL_VERIFYPEER, 0) curl.setopt(pycurl.SSL_VERIFYHOST, 0) buf = cStringIO.StringIO() curl

我想修改以下代码以运行“使用请求”模块。 我在网站上有以下代码:

def post(url, message, key, sign):

    curl = pycurl.Curl()
    curl.setopt(pycurl.URL, url)
    curl.setopt(pycurl.SSL_VERIFYPEER, 0)
    curl.setopt(pycurl.SSL_VERIFYHOST, 0)
    buf = cStringIO.StringIO()
    curl.setopt(pycurl.WRITEFUNCTION, buf.write)
    curl.setopt(pycurl.POSTFIELDS, message)
    curl.setopt(pycurl.HTTPHEADER, ['Key:' + key,
                                'Sign:' + (sign)])
    curl.perform()
    response = buf.getvalue()
    buf.close()
    return response        
我尝试使用请求访问网站,但使用以下代码因无效请求值而被拒绝:

def post(url, message, key, sign):
    import requests
    session = requests.session()
    session.headers = {'Key': key, 'Sign': sign}
    response = session.post(url, message)
    return response
我做错了什么,这些方法表现不一样

谢谢。

使用Pycurl:

POST /post HTTP/1.1
User-Agent: PycURL/7.32.0
Host: 127.0.0.1:4000
Accept: */*
Key:key
Sign:sign
Content-Length: 3
Content-Type: application/x-www-form-urlencoded

foo
根据请求:

POST /post HTTP/1.1
Host: 127.0.0.1:4000
Accept-Encoding: identity
Content-Length: 3
Key: key
Sign: sign

foo
有几个差异可能会导致您的错误:

  • 缺少
    用户代理
    接受
    标题。这是因为您覆盖了包含这些默认标题的
    session.headers
    属性。请尝试以下方法:

    session.headers.update({'Key':Key,'Sign':Sign})

  • 缺少
    内容类型
    标题。我想您传递了一个字符串作为
    消息
    参数。 请求不知道这是
    application/x-www-form-urlencoded
    ,因此不设置相关的头。 要么:

    • 自己设置标题
    • 更好的方法是:向请求传递参数字典。它们将被正确编码和声明

您应该添加回溯。如果它与ssl证书有关,那么请尝试使用session.post(url、message、verify=False)我没有回溯,因为没有python故障。该错误已从网站返回。。。