Python请求发布pdf响应406

时间:2018-12-13 06:16:44

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

我正在尝试使用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) 

the target url information:

错误消息:

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

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

您应该再添加两个参数Content-TypeReferer,但是请记住您不能在headers(param)中指定Content-Type。上传时,文件和标头中的Content-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)