【问题标题】:Python Requests post pdf response 406Python 请求发布 pdf 响应 406
【发布时间】:2018-12-13 06:16:44
【问题描述】:

我正在尝试使用 Requests lib post 方法将 pdf 上传到 http://www.pdfonline.com/convert-pdf-to-html/,但收到 406 错误:

url_gem = 'http://www2.hkexnews.hk/-/media/HKEXnews/Homepage/New-Listings/New-Listing-Information/New-Listing-Report/GEM/e_newlistings.pdf'
response_down = requests.get(url_gem)
with open('GEM.pdf', 'wb+') as f:
    f.write(response_down.content)
converter_url = 'http://207.135.71.158:8080/upload'

file = {'file': open('GEM.pdf', 'rb')}
headers = {'Accept': "application/pdf,.pdf", 'Content-Type':"multipart/form-data",
           'Cache-Control': "no-cache", 'User-Agent': 'Mozilla/5.0 (X11; '
            'Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) '
            'Chrome/54.0.2840.90 Safari/537.36'}
response = requests.post(converter_url, files = file, headers = headers)

print(response)
print(response.status_code)
print(response.headers) 

错误信息:

<Response [406]>
406
{'Content-Length': '0', 'Date': 'Thu, 13 Dec 2018 06:03:25 GMT'}
Process finished with exit code 0

任何帮助将不胜感激。

【问题讨论】:

  • 尝试仅使用'User-Agent': 'Mozilla/5.0 (X11; ' 'Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/54.0.2840.90 Safari/537.36' 标头发送。我不确定.pdf 是有效的 MIME 类型
  • 如果我在 headers 中没有“Accept”,服务器将返回 500 给我。
  • @Andersson 并不是说​​您不应该发送 Accept 标头,他只是意味着您应该从其值中删除“,.pdf”部分。
  • 删除 ",.pdf" 后,仍然是 406 。

标签: python-3.x pdf python-requests


【解决方案1】:

您应该再添加两个参数Content-TypeReferer,但请记住您不能在 headers(param) 中指定 Content-TypeContent-Type 上传时文件和标题完全不同。

编辑:导致 406 响应的重要原因是您没有指定文件内容类型

Whats Content-Type value within a HTTP-Request when uploading content?

import requests

converter_url = 'http://207.135.71.158:8080/upload'

file = {'file': ("GEM.pdf", open('GEM.pdf', 'rb'), "application/pdf")}
headers = {
    "Origin": "http://www.pdfonline.com",
    "Referer": "http://www.pdfonline.com/convert-pdf-to-html/",
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'}

response = requests.post(converter_url, files = file, headers = headers)

print(response.text)
print(response.status_code)
print(response.headers)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-13
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 2021-11-06
    相关资源
    最近更新 更多