2

I am doing a simple POST request using the requests module, and testing it against httpbin

import requests

url      = 'http://httpbin.org/post'
params   = {'apikey':'666666'}
sample   = {'sample': open('test.bin', 'r')}

response = requests.post( url, files=sample, params=params, verify=False)
report_info = response.json()
print report_info

I have an issue with the encoding. It is not using application/octet-stream and so the encoding is not correct. From the headers, I see:

{
  u'origin': u'xxxx, xxxxxx', 
  u'files': {
               u'sample': u'data:None;base64,qANQR1DBw..........

So, I get data:None instead of data:application/octet-stream when I try with curl. The file size and encoding is incorrect.

How can I force or check that it is using application/octet-stream?

1 Answer 1

1

Sample taken from http://www.python-requests.org/en/latest/user/quickstart/#custom-headers

>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> headers = {'content-type': 'application/json'}

>>> r = requests.post(url, data=json.dumps(payload), headers=headers)

You might want to change the headers to

headers = {'content-type': 'application/octet-stream'}
response = requests.post( url, files=sample, params=params, verify=False,
             headers = headers)
3
  • Thanks @thefourtheye for the suggestion, and while that does add the correct text to the header, it doesn't change the encoding. The file is still getting encoded incorrectly. It is as if python-requests is not recognising the file type correctly and so it doesn't encode correctly and it doesn't add the 'application/octet-stream' correctly. Oct 28, 2013 at 11:47
  • Using python requests: 'Content-Type': 'multipart/form-data; boundary=9e13cb8a968a49c2b7c8781e701d2c13'. Using curl: Content-Type": "multipart/form-data; boundary=------------------------d0f3782a702ecbd9. Why is it different? Oct 28, 2013 at 12:39
  • The boundary string is pseudo-random; as long as you're consistent within the same HTTP request, it's not a problem.
    – TML
    Apr 23, 2014 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.