如何(简单)生成从Java POST HTTP请求做文件上传 [英] how to (simply) generate POST http request from java to do the file upload
问题描述
我想上传使用HTTP POST从事件的Java应用程序/小程序文件。我想避免使用不包含在SE任何库,除非没有其他(可行)选项。结果
到目前为止,我想出只有非常简单的解决方案。结果
- 创建字符串(缓冲区),并兼容头填充它( http://www.ietf.org/ RFC / rfc1867.txt )结果
- 打开连接到服务器URL.openConnection()和将此文件写入OutputStream的内容。结果
我还需要二进制文件手动转换成POST事件。搜索结果
我希望有一些更好的,更简单的方式来做到这一点?
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?
推荐答案
您需要使用的java.net.URL
和 java.net .URLConnection
类。
有在 HTTP一些很好的例子:// java的。 sun.com/docs/books/tutorial/networking/urls/readingWriting.html
下面是一些快速和肮脏code:
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();
}
请注意,您可能仍然需要它写入连接之前urlen code()的POST数据。
Note that you may still need to urlencode() your POST data before writing it to the connection.
这篇关于如何(简单)生成从Java POST HTTP请求做文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!