HTTPS POST请求Python,返回.csv [英] HTTPS POST request Python, returning .csv

查看:348
本文介绍了HTTPS POST请求Python,返回.csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向HTTPS站点发出发布请求,该请求应以.csv文件作为响应.我有以下Python代码:

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)

=>给出BadStatusLine:''错误

=> 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]

输出:

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>

我做错了什么?如何捕捉"返回的.csv文件? 我尝试了使用Chrome扩展程序(Advanced Rest Client,并且正在运行...)的POST请求

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...)

推荐答案

出现302错误的HTML输出是因为您正在使用HTTP而不是HTTPS连接到站点,这在您的代码中:

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.

如果我尝试执行此操作,则可以使用请求,该请求非常清晰地包含文档.使用Requests的代码将类似于:

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)

CSV文件应位于r.content中,可以将其写入文件.

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

这篇关于HTTPS POST请求Python,返回.csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆