【问题标题】:Unable to post file in Python [Working in Java]无法在 Python 中发布文件 [使用 Java]
【发布时间】:2020-10-10 00:58:59
【问题描述】:

我对 Python 还是很陌生,我一直在尝试通过随请求一起发送一个 xml 文件来在 Python 中发出一个 post 请求。在 Java 中,我可以用下面的代码完美地做到这一点

String url = "https://www.test.com"
URL object = new URL(url);
HttpURLConnection conn = (HttpURLConnection) object.openConnection();

conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "application/xml");
conn.setRequestProperty("Accept", "application/xml");
conn.setRequestMethod("POST");

BufferedReader br = new BufferedReader((new FileReader("D:\\test.xml")));
String line1;
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
while ((line1 = br.readLine()) != null) {
    wr.write(line1);
    }

wr.flush();
wr.close();

int HttpResult = conn.getResponseCode();

为了让它在 Python 中工作,我尝试了不同的方法。他们都没有工作

    headers = {"Content-type": "application/xml",
                "Accept": "application/xml",
                }
    url = "https://www.test.com"
    filePath = "D:\\test.xml"
    file_data = [('file', (filePath, open(filePath), 'application/xml'))]
    resp = requests.post(url = url, files=file_data, headers=headers)

    print("resp=",resp.url)
    print("resp=",resp)

还有一些其他选择

    files = {'file':(filePath, open(filePath, 'rb'))}
    files = {'file': (filePath, open(filePath, 'rb'), 'application/xml', {'Accept': 'application/xml'})}

即使我尝试将文件作为数据发送。但无济于事。

    data = open("D:\\test.xml", 'rb').read()
    resp = requests.post(url = url, data=data, headers=headers)

请帮助我了解我错在哪里。几个小时以来,我一直在头疼。 仅供参考:我使用的是 Python 3.6.1

【问题讨论】:

  • 你的最后一个选项应该有效。
  • 请注意,查看发送的请求可能很有用,这应该在resp.request中可用
  • 不,它没有用。得到 404。这是否意味着请求命中服务器并且服务器以 404 响应?如果是这种情况,我应该要求检查服务器日志。
  • @OlvinR​​oght 它确实有效。在分析服务器日志时,发现 URL 的查询参数中存在问题。提供正确的查询参数后,它就可以工作了。
  • @GokuBalu,太棒了!很高兴您解决了这个问题。

标签: java python post python-requests httpurlconnection


【解决方案1】:

requests的官方文档,可以找到这个例子(根据你的情况改编):

url = "https://www.test.com"
filePath = "D:\\test.xml"
files = {'file': (filePath, open(filePath, 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
r = requests.post(url, files=files)

原始快速入门示例在这里:
https://requests.readthedocs.io/en/master/user/quickstart/#post-a-multipart-encoded-file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 2017-06-23
    • 2016-06-07
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多