`
gaojingsong
  • 浏览: 1153248 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

【基于HttpURLConnection模拟Http协议上传文件】

阅读更多

永久链接: http://gaojingsong.iteye.com/blog/2414484

预览文章: 【Http文件上传协议解析】

首先是请求头:

最重要的内容是Content-Type,他的内容中是:

Content-Type: multipart/form-data; boundary=----WebKitFormBoundary6TAB8KxvuJTZYfUn

用分号隔开了不同的参数: 

第一个参数multipart/form-data是必须的,是指提交的表单中有附件 

第二个参数boundary表示分割线,请求体中会用来分割不同的请求参数 

至于其他参数,在自己写请求的时候直接模仿传过去即可。

 

核心代码

package com.example.fileupload.controller;

 

import java.io.BufferedReader;

import java.io.DataOutputStream;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.HashMap;

import java.util.Set;

 

public class HttpUrlConnectionDemo {

 

/**

* @param args

*/

public static void main(String[] args) {

// 上传文件测试

String actionURL ="http://localhost:9090/mgr/upload";

String uploadFile="c:/examples.cfg";

HashMap<String, String> parameters = new HashMap<String, String>();

parameters.put("email", "demo@123.com");

singleFileUploadWithParameters( actionURL,  uploadFile, parameters );

 

}

 

/** 

* @author Johnson 

* @method singleFileUploadWithParameters 

* @description 集上传单个文件与传递参数于一体的方法 

* @param actionURL 上传文件的URL地址包括URL 

* @param fileType 文件类型(枚举类型) 

* @param uploadFile 上传文件的路径字符串 

* @return String("" if no response get) 

* @attention 上传文件name为file(服务器解析) 

* */  

public static String singleFileUploadWithParameters(String actionURL, String uploadFile, 

HashMap<String, String> parameters){  

   String end = "\r\n";  

   String twoHyphens = "--";  

   String boundary = "---------------------------7e0dd540448";  

   String response = "";  

   try{  

       URL url = new URL(actionURL);  

       HttpURLConnection connection = (HttpURLConnection)url.openConnection();  

       //发送post请求需要下面两行  

       connection.setDoInput(true);  

       connection.setDoOutput(true);  

       //设置请求参数  

       connection.setUseCaches(false);  

       connection.setRequestMethod("POST");  

       connection.setRequestProperty("Connection", "Keep-Alive");  

       connection.setRequestProperty("Charset", "UTF-8");  

       connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);  

       //获取请求内容输出流                          

       DataOutputStream ds = new DataOutputStream(connection.getOutputStream());  

       String fileName = uploadFile.substring(uploadFile.lastIndexOf("/") + 1);  

       //开始写表单格式内容  

       //写参数  

       Set<String> keys = parameters.keySet();  

       for(String key : keys){  

           ds.writeBytes(twoHyphens + boundary + end);  

           ds.writeBytes("Content-Disposition: form-data; name=\"");  

           ds.write(key.getBytes());  

           ds.writeBytes("\"" + end);  

           ds.writeBytes(end);  

           ds.write(parameters.get(key).getBytes());  

           ds.writeBytes(end);  

       }  

       //写文件  

       ds.writeBytes(twoHyphens + boundary + end);  

       ds.writeBytes("Content-Disposition: form-data; " + "name=\"file1\"; " + "filename=\"");  

       //防止中文乱码  

       ds.write(fileName.getBytes());  

       ds.writeBytes("\"" + end);  

       ds.writeBytes("Content-Type: text/plain" + end);  

       ds.writeBytes(end);  

       //根据路径读取文件  

       FileInputStream fis = new FileInputStream(uploadFile);  

       byte[] buffer = new byte[1024];  

       int length = -1;  

       while((length = fis.read(buffer)) != -1){  

           ds.write(buffer, 0, length);  

       }  

       ds.writeBytes(end);  

       fis.close();  

       ds.writeBytes(twoHyphens + boundary + twoHyphens + end);  

       ds.writeBytes(end);  

       ds.flush();  

       try{  

           //获取URL的响应  

           BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));  

           String s = "";  

           String temp = "";  

           while((temp = reader.readLine()) != null){  

               s += temp;  

           }  

           response = s;  

           reader.close();  

       }catch(IOException e){  

           e.printStackTrace();  

           System.out.println("No response get!!!");  

       }  

       ds.close();  

   }catch(IOException e){  

       e.printStackTrace();  

       System.out.println("Request failed!");  

   }  

   return response;  

}  

 

}

 

 

结果验证:



 

  • 大小: 239.9 KB
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics