Sunny
Sunny

Reputation: 45

Python Requests post pdf response 406

I am trying to use Requests lib post method to upload a pdf to http://www.pdfonline.com/convert-pdf-to-html/ , but I am receiving 406 error :

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:

Error message:

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

Any help would be appreciated.

Upvotes: 2

Views: 2387

Answers (1)

KC.
KC.

Reputation: 3107

You should add two more parameters Content-Type and Referer, but remember you can not specify Content-Type in headers(param). Content-Type in files and headers are totally different when you are uploading.

Edit: the vital reason leaded 406 response is you did not specify file content-type

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)

Upvotes: 3

Related Questions