java post 二进制上传,如何(简单)生成从Java POST HTTP请求做文件上传

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?

解决方案

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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值