java 如何(简单地)从java生成POST http请求来进行文件上传
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/314300/
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
how to (simply) generate POST http request from java to do the file upload
提问by user40271
I would like to upload files from java application/applet using POST http event. I would like to avoid to use any library not included in SE, unless there is no other (feasible) option.
So far I come up only with very simple solution.
- Create String (Buffer) and fill it with compatible header (http://www.ietf.org/rfc/rfc1867.txt)
- Open connection to server URL.openConnection() and write content of this file to OutputStream.
I also need to manually convert binary file into POST event.
I hope there is some better, simpler way to do this?
我想使用 POST http 事件从 java 应用程序/小程序上传文件。我想避免使用任何未包含在 SE 中的库,除非没有其他(可行的)选项。
到目前为止,我只提出了非常简单的解决方案。
- 创建字符串(缓冲区)并用兼容的标头填充它(http://www.ietf.org/rfc/rfc1867.txt)
- 打开与服务器 URL.openConnection() 的连接并将此文件的内容写入 OutputStream。
我还需要手动将二进制文件转换为 POST 事件。
我希望有一些更好、更简单的方法来做到这一点?
回答by Alnitak
You need to use the java.net.URLand java.net.URLConnectionclasses.
您需要使用java.net.URL和java.net.URLConnection类。
There are some good examples at http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html
http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html 上有一些很好的例子
Here's some quick and nasty code:
这是一些快速而讨厌的代码:
public void post(String url) throws Exception {
URL u = new URL(url);
URLConnection c = u.openConnection();
c.setDoOutput(true);
if (c instanceof HttpURLConnection) {
((HttpURLConnection)c).setRequestMethod("POST");
}
OutputStreamWriter out = new OutputStreamWriter(
c.getOutputStream());
// output your data here
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
c.getInputStream()));
String s = null;
while ((s = in.readLine()) != null) {
System.out.println(s);
}
in.close();
}
Note that you may still need to urlencode() your POST data before writing it to the connection.
请注意,在将 POST 数据写入连接之前,您可能仍需要对其进行 urlencode()。
回答by Josh
You need to learn about the chunked encoding used in newer versions of HTTP. The Apache HttpClient library is a good reference implementation to learn from.
您需要了解新版本的 HTTP 中使用的分块编码。Apache HttpClient 库是一个很好的参考实现,可以学习。

