用URL请求做文件上传

来源:互联网 发布:程序员很难找女朋友吗 编辑:程序博客网 时间:2024/06/04 19:38

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


原创粉丝点击