2008-11-24 78 views
3

我想用java http应用程序/ applet从java应用程序上传文件。除非没有其他(可行)选项,否则我想避免使用任何未包含在SE中的库。
到目前为止,我只想出了非常简单的解决方案。
- 创建字符串(缓冲区)并填充兼容头(http://www.ietf.org/rfc/rfc1867.txt
- 打开与服务器URL.openConnection()的连接并将此文件的内容写入OutputStream。
我还需要手动将二进制文件转换为POST事件。

我希望有更好,更简单的方法来做到这一点?如何(简单地)从java生成POST http请求来做文件上传

+0

请解释你为什么不想使用外部库。显然它是*可能*没有任何外部库,但你基本上会复制(说)HttpClient(http://hc.apache.org/httpcomponents-client/index.html) – 2008-11-24 14:46:00

回答

3

您需要了解在较新版本的HTTP中使用的分块编码。 Apache HttpClient库是一个很好的参考实现。

8

您需要使用java.net.URLjava.net.URLConnection类。

有在http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html

一些很好的例子下面是一些快速和肮脏的代码:

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(); 
} 

请注意,您可能仍然需要将其写入连接之前来urlencode()的POST数据。