利用HttpURLConnection发送post请求上传文件

在页面里实现上传文件不是什么难事,写个form,加上enctype = "multipart/form-data",在写个接收的就可以了,没什么难的,如果要用java.net.HttpURLConnection来实现文件上传,还真有点搞头.:-)

1.先写个servlet把接收到的 HTTP 信息保存在一个文件中, 看一下 form 表单到底封装了什么样的信息。

Java代码 复制代码
  1. public void doPost(HttpServletRequest request, HttpServletResponse response)   
  2.            throws ServletException, IOException {   
  3.        //获取输入流,是HTTP协议中的实体内容   
  4.        ServletInputStream  in=request.getInputStream();   
  5.        //缓冲区   
  6.        byte buffer[]=new byte[1024];   
  7.        FileOutputStream out=new FileOutputStream("d://test.log");   
  8.        int len=sis.read(buffer, 01024);   
  9.        //把流里的信息循环读入到file.log文件中   
  10.        while( len!=-1 ){   
  11.            out.write(buffer, 0, len);   
  12.            len=in.readLine(buffer, 01024);   
  13.   
  14.        }   
  15.        out.close();   
  16.        in.close();   
  17.     }  
public void doPost(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
       //获取输入流,是HTTP协议中的实体内容
       ServletInputStream  in=request.getInputStream();
       //缓冲区
       byte buffer[]=new byte[1024];
       FileOutputStream out=new FileOutputStream("d://test.log");
       int len=sis.read(buffer, 0, 1024);
       //把流里的信息循环读入到file.log文件中
       while( len!=-1 ){
           out.write(buffer, 0, len);
           len=in.readLine(buffer, 0, 1024);

       }
       out.close();
       in.close();
    }

 来一个form表单。

  <form name="upform" action="upload.do" method="POST"
            enctype="multipart/form-data">
            参数<input type="text" name="username"/><br/>
            文件1<input type="file" name="file1"/><br/>
            文件2<input type="file" name="file2"/><br/>
            <input type="submit" value="Submit" />
            <br />
     </form>

假如我参数写的内容是hello word,然后二个文件是二个简单的txt文件,上传后test.log里如下

Java代码 复制代码
  1. -----------------------------7da2e536604c8   
  2. Content-Disposition: form-data; name="username"  
  3.   
  4. hello word   
  5. -----------------------------7da2e536604c8   
  6. Content-Disposition: form-data; name="file1"; filename="D:/haha.txt"  
  7. Content-Type: text/plain   
  8.   
  9. haha   
  10.   hahaha   
  11. -----------------------------7da2e536604c8   
  12. Content-Disposition: form-data; name="file2"; filename="D:/huhu.txt"  
  13. Content-Type: text/plain   
  14.   
  15. messi    
  16. huhu   
  17. -----------------------------7da2e536604c8--  
-----------------------------7da2e536604c8
Content-Disposition: form-data; name="username"

hello word
-----------------------------7da2e536604c8
Content-Disposition: form-data; name="file1"; filename="D:/haha.txt"
Content-Type: text/plain

haha
  hahaha
-----------------------------7da2e536604c8
Content-Disposition: form-data; name="file2"; filename="D:/huhu.txt"
Content-Type: text/plain

messi 
huhu
-----------------------------7da2e536604c8--

 

 研究下规律发现有如下几点特征

1.第一行是“ -----------------------------7d92221b604bc ”作为分隔符,然后是“ /r/n ” 回车换行符。 这个7d92221b604bc 分隔符浏览器是随机生成的。

2.第二行是Content-Disposition: form-data; name="file2"; filename="D:/huhu.txt";name=对应input的name值,filename对应要上传的文件名(包括路径在内),

3.第三行如果是文件就有Content-Type: text/plain;这里上传的是txt文件所以是text/plain,如果上穿的是jpg图片的话就是image/jpg了,可以自己试试看看。

然后就是回车换行符。

4.在下就是文件或参数的内容或值了。如:hello word。

5.最后一行是-----------------------------7da2e536604c8--,注意最后多了二个--;

 

有了这些就可以使用HttpURLConnection来实现上传文件功能了

Java代码 复制代码
  1. public void upload(){   
  2.         List<String> list  = new ArrayList<String>();  //要上传的文件名,如:d:/haha.doc.你要实现自己的业务。我这里就是一个空list.   
  3.         try {   
  4.             String BOUNDARY = "---------7d4a6d158c9"// 定义数据分隔线   
  5.             URL url = new URL("http://localhost/JobPro/upload.do");   
  6.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();   
  7.             // 发送POST请求必须设置如下两行   
  8.             conn.setDoOutput(true);   
  9.             conn.setDoInput(true);   
  10.             conn.setUseCaches(false);   
  11.             conn.setRequestMethod("POST");   
  12.             conn.setRequestProperty("connection""Keep-Alive");   
  13.             conn.setRequestProperty("user-agent""Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");   
  14.             conn.setRequestProperty("Charsert""UTF-8");    
  15.             conn.setRequestProperty("Content-Type""multipart/form-data; boundary=" + BOUNDARY);   
  16.                
  17.             OutputStream out = new DataOutputStream(conn.getOutputStream());   
  18.             byte[] end_data = ("/r/n--" + BOUNDARY + "--/r/n").getBytes();// 定义最后数据分隔线   
  19.             int leng = list.size();   
  20.             for(int i=0;i<leng;i++){   
  21.                 String fname = list.get(i);   
  22.                 File file = new File(fname);   
  23.                 StringBuilder sb = new StringBuilder();     
  24.                 sb.append("--");     
  25.                 sb.append(BOUNDARY);     
  26.                 sb.append("/r/n");     
  27.                 sb.append("Content-Disposition: form-data;name=/"file"+i+"/";filename=/""+ file.getName() + "/"/r/n");     
  28.                 sb.append("Content-Type:application/octet-stream/r/n/r/n");     
  29.                    
  30.                 byte[] data = sb.toString().getBytes();   
  31.                 out.write(data);   
  32.                 DataInputStream in = new DataInputStream(new FileInputStream(file));   
  33.                 int bytes = 0;   
  34.                 byte[] bufferOut = new byte[1024];   
  35.                 while ((bytes = in.read(bufferOut)) != -1) {   
  36.                     out.write(bufferOut, 0, bytes);   
  37.                 }   
  38.                 out.write("/r/n".getBytes()); //多个文件时,二个文件之间加入这个   
  39.                 in.close();   
  40.             }   
  41.             out.write(end_data);   
  42.             out.flush();     
  43.             out.close();    
  44.                
  45.             // 定义BufferedReader输入流来读取URL的响应   
  46.             BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));   
  47.             String line = null;   
  48.             while ((line = reader.readLine()) != null) {   
  49.                 System.out.println(line);   
  50.             }   
  51.   
  52.         } catch (Exception e) {   
  53.             System.out.println("发送POST请求出现异常!" + e);   
  54.             e.printStackTrace();   
  55.         }   
  56.     }  

至于接收文件上传,可以浏览本博客中文章利用commons-fileupload 实现文件上传终极版及commons-fileupload和commons-io包关系

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值