python如何解码http响应 [英] python how to decode http response

查看:391
本文介绍了python如何解码http响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码从api端点登录并检索数据,但似乎响应已编码,因此我无法读取内容.我正在使用请求requestes-0.0.1

i am using the below code to login and retrieve data from an api endpoint but seems the response see encoded and i am not able to read the content. i am using request requestes-0.0.1

import requests
import json
import os


http_proxy  = "http://192.168.10.20:8888"
https_proxy = "https://192.168.10.20:8888"

proxyDict = {
              "http"  : http_proxy,
              "https" : https_proxy,
            }
session = requests.Session()

payloadopt = 'user_id=tom&password=xxxxx'
s = session.post('https://login.milock.com/api/login',data=payloadopt, proxies=proxyDict, verify=False, headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0', 'Accept':'application/json, text/plain, */*', 'Accept-Language':'en-US,en;q=0.5', 'Accept-Encoding':'gzip, deflate, br', 'Content-Type':'application/x-www-form-urlencoded'}, stream=True)

在控制台上打印相同内容时的响应

response when i print the same on console

▒▒7▒E`▒▒YD▒▒k▒샄▒q▒▒f,▒▒G▒(U▒Uv▒4ڍ▒߼w&▒▒!Ψ▒▒▒▒E5Q▒_▒▒{▒F▒▒<.▒▒▒▒4▒▒> p{▒k9▒▒֏9▒▒

有人可以告诉我如何解码和读取响应中的数据

Can someone tell me how can decode and read the data from the response

推荐答案

响应使用 brotli 压缩.标准库不支持此压缩方法.您可以从pypi安装第三方软件包以将其解压缩-有许多可用的软件包.

The response is encoded with brotli compression. This compression method isn't supported by the standard library. You can install a third party package from pypi to decompress it - a number of packages are available.

例如

$ pip install brotli

>>> import brotli
>>> decompressed = brotli.decompress(response.content)
>>> dict_ = json.loads(decompressed)

如果您不想避免安装第三方模块,请从请求中的"accept-encoding"标头中删除'br':

If you'd prefer to avoid installing a third party module, remove 'br' from the 'accept-encoding' header in the request:

'Accept-Encoding':'gzip, deflate, br' -> 'Accept-Encoding':'gzip, deflate'

这篇关于python如何解码http响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆