RESTful API发布请求

问题描述 投票:0回答:1

我正在向API发出请求,我正在使用基本授权,但由于某些原因,该API无法解码授权字符串

这是我正在使用的代码:

import base64,requests
from base64 import b64encode

url = 'api.sample/test'

APIuser = b'generic_user'
APIpass = b'generic_pass'

myobj = {"data1_field":"data1"}

data_string = APIuser + b":" + APIpass
data_bytes = b64encode(data_string).decode('ascii')

head = {'Content-Type':'application/json', 'Accept':'*/*','Authorization':'Basic ' + data_bytes}

x = requests.post(url, headers=head,
        data = myobj)

print(x.text)

这是我得到的错误:

{
  "error": {
    "detail": "Cannot decode: java.io.StringReader@45fab9",
    "message": "Exception while reading request"
  },
  "status": "failure"
}

关于我在做什么错的任何想法?

python python-3.x rest python-requests encode
1个回答
0
投票

B64在python上被读取为字节数据,因此该字符串将被表示为b'x',因此其实现方式是在响应上发送加密类型,同样,我也在使用ascii编码,并且需要使用是utf8,重要的是不要与utf-8混淆(对于编译器来说显然不一样)

url = "api.sample/test"

payload = "{\"Data1\": \"Data1_field\"}

headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Basic get the string'
}

response = requests.request("POST", url, headers=headers, data = payload)

print(response.text.encode('utf8'))
© www.soinside.com 2019 - 2024. All rights reserved.