【问题标题】:Using requests to send byte-array to webservice using http post使用请求将字节数组发送到使用 http post 的 web 服务
【发布时间】:2016-06-16 23:34:04
【问题描述】:

目前我正在尝试将字节数组发送到 Web 服务,但我收到错误消息,字节数组不可序列化:

TypeError: bytearray(b'') is not JSON serializable

我正在使用以下代码

发送请求

# Set blob
with open('demo-file.txt') as file:
    f = file.read()
    b = bytearray(f)
    print a.set_data('5cb9bc4d-c0fd-40ab-8b74-4e62b50d8966', b)

Set_Data 方法:

def set_data(self, path, data):
    """
    Save data in

    Parameter
    --------
    path (str): Path as string
    data (bytearray): Data as bytearray
    """

    result = requests.post(self.url + '/set', json = { 'path': path, 'data': data})

    # Check status and token
    if result.status_code == 200:
        return result.text

我做错了什么,我必须使用其他一些方法来发送字节数组吗?

非常感谢大家!

【问题讨论】:

    标签: python json python-2.7 bytearray python-requests


    【解决方案1】:

    如果你真的需要 json,你必须对你的二进制数据进行编码。见:Base64 encoding in Python 3

    另一种选择:How to send binary post data via HTTP?

    【讨论】:

    • 是的,我通常在 c# 中使用 Newtonsoft json 并自动进行 base64 转换。谢谢,以前不知道!
    猜你喜欢
    • 2017-07-14
    • 1970-01-01
    • 2011-09-17
    • 2016-09-24
    • 1970-01-01
    • 2013-05-14
    • 2013-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多