如何使用请求修复 Python 中的“415 Unsupported Media Type”错误

How to fix '415 Unsupported Media Type' error in Python using requests

我想使用 bitbucket 的 rest 创建一个提交 api。至此,所有关于Response 415的问题的答案都通过将header中的Content-Type设置为application/json;charset-UTF8来解决。但是,这并不能解决我得到的响应。

所以这就是我正在尝试做的事情:

import requests

def commit_file(s, path, content, commit_message, branch, source_commit_id):
    data = dict(content=content, message=commit_message, branch=branch, sourceCommitId=source_commit_id)
    r = s.put(path, data=data, headers={'Content-type': 'application/json;charset=utf-8'})
    return r.status_code

s = requests.Session()
s.auth = ('name', 'token')
url = 'https://example.com/api/1.0/projects/Project/repos/repo/browse/file.txt'
file = s.get(url)
r = commit_file(s, url, file.json() , 'Commit Message', 'test', '51e0f6faf64')

GET 请求成功 returns 文件,我想将其内容提交到确实存在的分支 test 上。

无论Content-Type,响应的status_code都是415

这是放置请求的header:

OrderedDict([('user-agent', ('User-Agent', 'python-requests/2.21.0')), ('accept-encoding', ('Accept-Encoding', 'gzip, deflate')), ('accept', ('Accept', '*/*')), ('connection', ('Connection', 'keep-alive')), ('content-type', ('Content-type', 'application/json;charset=utf-8')), ('content-length', ('Content-Length', '121')), ('authorization', ('Authorization', 'Basic YnVybWF4MDA6Tnp...NkJqWGp1a2JjQ3dNZzhHeGI='))])

This 解释了 curl 的用法以及文件何时在本地可用。当如上所示检索文件内容时,python 中的正确请求会是什么样子?

这是使用 MultipartEncoder:

的解决方案
import requests
import requests_toolbelt.multipart.encoder

def commit_file(s, path, content, commit_message, branch, source_commit_id):
    data = requests_toolbelt.MultipartEncoder(
        fields={
            'content': content,
            'message': commit_message,
            'branch': branch,
            'sourceCommitId': source_commit_id
        }
    )
    r = s.put(path, data=data, headers={'Content-type': data.content_type})

内容类型 application/json;charset=utf-8 不正确。

根据文档,您必须发送多部分表单数据。您不能使用 JSON.

This resource accepts PUT multipart form data, containing the file in a form-field named content.

参见:How to send a "multipart/form-data" with requests in python?