HTTPS POST request Python, returning .csv

故事扮演 提交于 2019-12-10 11:15:56

问题


I want to make a post request to a HTTPS-site that should respond with a .csv file. I have this Python code:

try:
    #conn = httplib.HTTPSConnection(host="www.site.com", port=443)

=> Gives an BadStatusLine: ' ' error

    conn = httplib.HTTPConnection("www.site.com");
    params  = urllib.urlencode({'val1':'123','val2':'abc','val3':'1b3'})
    conn.request("POST", "/nps/servlet/exportdatadownload", params)
    content = conn.getresponse()
    print content.reason, content.status
    print content.read()
    conn.close()
except:
    import sys
    print sys.exc_info()[:2]

Output:

Found 302

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<HTML><HEAD>
<TITLE>302 Found</TITLE>
</HEAD><BODY>
<H1>Found</H1>
The document has moved <A HREF="https://www.site.com/nps/servlet/exportdatadownload">here</A>.<P>
<HR>
<ADDRESS>Oracle-Application-Server-10g/10.1.3.5.0 Oracle-HTTP-Server Server at mp-www1.mrco.be Port 7778</ADDRESS>
</BODY></HTML>

What am I doing wrong? How do I 'catch' the returning .csv file? I tried the POST request with an Chrome Extentions (Advanced Rest Client, and that's working...)


回答1:


The HTML output with the 302 error is because you're connecting to the site using HTTP instead of HTTPS, which is in your code here:

conn = httplib.HTTPConnection("www.site.com");

Presumably you're doing that because of some other error with the commented out section of your code.

If I were trying to do this I would use Requests, which comes with very clear documentation. With Requests the code would be something like:

import requests

url = "https://www.example.com/nps/servlet/exportdatadownload"
payload = { "val1": "123", "val2": "abc", "val3": "1b3" }
r = requests.post(url, data=payload, verify=True)

The CSV file should be in r.content, which can be written to a file.



来源:https://stackoverflow.com/questions/15057847/https-post-request-python-returning-csv

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