java 如何发送 POST 请求并获得文件响应?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5159476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:45:04  来源:igfitidea点击:

How to send POST request and get file response?

javapostattachmenthttp-postcontent-disposition

提问by latata

I want to send POST request (like html form) and get file (HTTP header: "Content-Disposition: attachment; filename="myfile.pdf"). Can you help me?

我想发送 POST 请求(如 html 表单)并获取文件(HTTP 标头:“Content-Disposition:附件;文件名 =“myfile.pdf”)。你能帮我吗?

回答by aioobe

Your best option is probably to use a third party library such as HttpClientor HTMLUnit.

您最好的选择可能是使用第三方库,例如HttpClientHTMLUnit

If you prefer to do it with the standard API it's not that complicated.

如果您更喜欢使用标准 API 来做这件事,那就没那么复杂了。

// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + 
                                URLEncoder.encode("value1", "UTF-8");

data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" +
                                URLEncoder.encode("value2", "UTF-8");

// Send data
URL url = new URL("http://hostname:80/cgi");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();

// Get the response
BufferedReader rd = new BufferedReader(
        new InputStreamReader(conn.getInputStream()));

String line;
while ((line = rd.readLine()) != null) {
    // Process line...
}
wr.close();
rd.close();

回答by Brian Agnew

Check out HttpClient. There's a pretty comprehensive tutorial here.

查看HttpClient。有一个非常全面的教程在这里