如何(简单地)从java生成POST http请求来进行文件上传 [英] how to (simply) generate POST http request from java to do the file upload

查看:34
本文介绍了如何(简单地)从java生成POST http请求来进行文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 POST http 事件从 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.URLjava.net.URLConnection 类.

You need to use the java.net.URL and java.net.URLConnection classes.

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

请注意,在将 POST 数据写入连接之前,您可能仍需要对其进行 urlencode().

Note that you may still need to urlencode() your POST data before writing it to the connection.

这篇关于如何(简单地)从java生成POST http请求来进行文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆