您的位置:首页 > 其它

用URL请求做文件上传

2011-11-19 17:43 232 查看
JAVA可以用URL请求直接发送HTTP请求,和web server交互,就和浏览器一样。发送的内容格式是:

假设传的文件名是test.txt,内容是:

content of test.txt


-----------------------------7d65d38307d2
Content-Disposition: form-data; name="myfile"; filename="E:\badboy\test.txt"
Content-Type: text/plain

content of test.txt
-----------------------------7d65d38307d2--


代码概要如下:

URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);

//perform just like browser does when uploading files, using multipart/form-data
StringBuffer sb = new StringBuffer();
sb.append("--");
sb.append(CommonUtil.BOUNDRAY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data; name=\"pictureInfo.file\"; filename=\"" + picFileName + "\"\r\n");
sb.append("Content-Type: application/octet-stream\r\n\r\n");
byte[] start_data = sb.toString().getBytes();

byte[] end_data = ("\r\n--" + CommonUtil.BOUNDRAY + "--\r\n").getBytes();

conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + CommonUtil.BOUNDRAY);
conn.setRequestProperty("Content-Length", String.valueOf(start_data.length + pic_data.length + end_data.length)); //设置内容长度
conn.setConnectTimeout(CommonUtil.NETWORK_TIME_OUT);

BufferedOutputStream bos = new BufferedOutputStream(conn.getOutputStream());
bos.write(start_data);
bos.write(pic_data);
bos.write(end_data);
bos.flush();
bos.close();

conn.connect();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: