如何从Python中的HTTP GET响应获取字符串形式?

时间:2018-11-05 21:29:36

标签: python http get

我有以下任务

编写一个名为“ get_response”的函数,该函数按顺序表示三个字符串参数,分别表示协议,服务器名称和HTTP GET请求的路径。将HTTPS GET请求的响应返回到这些输入所形成的url。响应应以字符串形式返回

我编写了以下代码。

def get_response(protocol, server, path):
str = protocol + "://" + server + "/" + path
contents = urllib.request.urlopen(str).read()

return contents

运行代码时,我得到以下信息

  

b'学生'

问题想要的是字符串格式,答案中只有“学生”。我尝试将其转换为str,但无法正常工作。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

使用解码

    "variants": [
    {
        "id": 5,
        "name": "color",
        "item_id": 3,
        "created_at": "2018-11-02 15:08:19",
        "updated_at": "2018-11-02 15:08:19",
        "options": [
            {
                "id": 13,
                "name": "red",
                "variant_id": 5,
                "created_at": "2018-11-02 15:08:21",
                "updated_at": "2018-11-02 15:08:21"
            },
            {
                "id": 14,
                "name": "blue",
                "variant_id": 5,
                "created_at": "2018-11-02 15:08:21",
                "updated_at": "2018-11-02 15:08:21"
            },
            {
                "id": 15,
                "name": "green",
                "variant_id": 5,
                "created_at": "2018-11-02 15:08:22",
                "updated_at": "2018-11-02 15:08:22"
            }
        ]
    },
    {
        "id": 6,
        "name": "size",
        "item_id": 3,
        "created_at": "2018-11-02 15:08:19",
        "updated_at": "2018-11-02 15:08:19",
        "options": [
            {
                "id": 16,
                "name": "small",
                "variant_id": 6,
                "created_at": "2018-11-02 15:08:22",
                "updated_at": "2018-11-02 15:08:22"
            },
            {
                "id": 17,
                "name": "medium",
                "variant_id": 6,
                "created_at": "2018-11-02 15:08:22",
                "updated_at": "2018-11-02 15:08:22"
            },
            {
                "id": 18,
                "name": "large",
                "variant_id": 6,
                "created_at": "2018-11-02 15:08:22",
                "updated_at": "2018-11-02 15:08:22"
            }
        ]
    }
]