How to Use Python to Send a Multipart PDF Request to OneNote

蹲街弑〆低调 提交于 2019-12-08 08:02:31

The answer it turns out is that Python encodes blank lines as "\n" but OneNote requires "\r\n". It also requires a blank line ("\r\n") after the final boundary. Finally, it can't have any leading whitespace in the body (no indents) for the Content-Type and Content-Disposition lines. (There should also be a blank line after each Content-Disposition line.)

For example, if this was the body:

"""--MyBoundary
Content-Type: text/html
Content-Disposition: form-data; name="Presentation"

Some random text
--MyBoundary
Content-Type: text/text
Content-Disposition: form-data; name="more"; filename="more.txt"

More text
--MyBoundary--
"""

it should be represented by the string

'--MyBoundary\r\nContent-Type: text/html\r\nContent-Disposition: form-data; name="Presentation"\r\n\r\nSome random text\r\n--MyBoundary\r\nContent-Type: text/text\r\nContent-Disposition: form-data; name="more"; filename="more.txt"\r\n\r\nMore text\r\n--MyBoundary--\r\n' 

which can be made just by typing the text inside three """ quotes (which will automatically create \n in the final string wherever there's a blank line) and then replacing the "\n" with "\r\n":

body = body.replace("\n", "\r\n")

The headers would be:

headers = {"Content-Type":"multipart/form-data; boundary=MyBoundary",
           "Authorization" : "bearer " + access_token} 

Finally, you would POST the call like this:

session = requests.Session()
request = requests.Request(method="POST", headers=headers,
                           url=url,  data=body)
prepped = request.prepare()
response = session.send(prepped)

You need to construct the full HTTP request, not just send along the HTML.

For your body, try constructing the full body as you posted in your question.

--MyAppPartBoundary
Content-Disposition:form-data; name="Presentation"
Content-type:text/html

<!DOCTYPE html>
<html>
  // truncated
</html>

--MyAppPartBoundary
Content-Disposition:form-data; name="OfficeLeasePartName"
Content-type:application/pdf

... PDF binary data ...

--MyAppPartBoundary--

Make sure you set the content-type header correctly:

Content-Type:multipart/form-data; boundary=MyAppPartBoundary
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!