HttpClient通过Post上传文件(转)

在之前一段的项目中,使用Java模仿Http Post方式发送参数以及文件,单纯的传递参数或者文件可以使用URLConnection进行相应的处理。

          但是项目中涉及到既要传递普通参数,也要传递多个文件(不是单纯的传递XML文件)。在网上寻找之后,发现是使用HttClient来进行响应的操作,起初尝试多次依然不能传递参数和传递文件,后来发现时因为当使用HttpClient时,不能使用request.getParameter()对普通参数进行获取,而要在服务器端使用Upload来进行操作。

          HttpClient4.2 jar下载 :http://download.csdn.net/detail/just_szl/4370574

         客户端代码:

 

[java] view plain copy
 
  1. import java.io.ByteArrayOutputStream;  
  2. import java.io.File;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import org.apache.http.HttpEntity;  
  6. import org.apache.http.HttpResponse;  
  7. import org.apache.http.HttpStatus;  
  8. import org.apache.http.ParseException;  
  9. import org.apache.http.client.HttpClient;  
  10. import org.apache.http.client.methods.HttpPost;  
  11. import org.apache.http.entity.mime.MultipartEntity;  
  12. import org.apache.http.entity.mime.content.FileBody;  
  13. import org.apache.http.impl.client.DefaultHttpClient;  
  14. import org.apache.http.util.EntityUtils;  
  15.   
  16. /** 
  17.  *  
  18.  * @author <a href="mailto:just_szl@hotmail.com"> Geray</a> 
  19.  * @version 1.0,2012-6-12  
  20.  */  
  21. public class HttpPostArgumentTest2 {  
  22.   
  23.     //file1与file2在同一个文件夹下 filepath是该文件夹指定的路径      
  24.     public void SubmitPost(String url,String filename1,String filename2, String filepath){  
  25.           
  26.         HttpClient httpclient = new DefaultHttpClient();  
  27.           
  28.         try {  
  29.       
  30.             HttpPost httppost = new HttpPost(url);  
  31.               
  32.             FileBody bin = new FileBody(new File(filepath + File.separator + filename1));  
  33.                 
  34.             FileBody bin2 = new FileBody(new File(filepath + File.separator + filename2));  
  35.               
  36.             StringBody comment = new StringBody(filename1);  
  37.   
  38.             MultipartEntity reqEntity = new MultipartEntity();  
  39.               
  40.             reqEntity.addPart("file1", bin);//file1为请求后台的File upload;属性      
  41.              reqEntity.addPart("file2", bin2);//file2为请求后台的File upload;属性  
  42.              reqEntity.addPart("filename1", comment);//filename1为请求后台的普通参数;属性     
  43.             httppost.setEntity(reqEntity);  
  44.               
  45.             HttpResponse response = httpclient.execute(httppost);  
  46.               
  47.                   
  48.             int statusCode = response.getStatusLine().getStatusCode();  
  49.               
  50.                   
  51.             if(statusCode == HttpStatus.SC_OK){  
  52.                       
  53.                 System.out.println("服务器正常响应.....");  
  54.                   
  55.                 HttpEntity resEntity = response.getEntity();  
  56.                   
  57.                   
  58.                 System.out.println(EntityUtils.toString(resEntity));//httpclient自带的工具类读取返回数据  
  59.                   
  60.                   
  61.                   
  62.                 System.out.println(resEntity.getContent());     
  63.   
  64.                 EntityUtils.consume(resEntity);  
  65.             }  
  66.                   
  67.             } catch (ParseException e) {  
  68.                 // TODO Auto-generated catch block  
  69.                 e.printStackTrace();  
  70.             } catch (IOException e) {  
  71.                 // TODO Auto-generated catch block  
  72.                 e.printStackTrace();  
  73.             } finally {  
  74.                 try {   
  75.                     httpclient.getConnectionManager().shutdown();   
  76.                 } catch (Exception ignore) {  
  77.                       
  78.                 }  
  79.             }  
  80.         }  
  81.       
  82.       
  83.     /** 
  84.      * @param args 
  85.      */  
  86.     public static void main(String[] args) {  
  87.         // TODO Auto-generated method stub  
  88.           
  89.         HttpPostArgumentTest2 httpPostArgumentTest2 = new HttpPostArgumentTest2();  
  90.           
  91.         httpPostArgumentTest2.SubmitPost("http://127.0.0.1:8080/demo/receiveData.do",  
  92.                 "test.xml","test.zip","D://test");  
  93.     }  
  94.       
  95. }  

服务端代码:

 

 

[java] view plain copy
 
  1. public void receiveData(HttpServletRequest request, HttpServletResponse response) throws AppException{  
  2.   
  3.         PrintWriter out = null;  
  4.         response.setContentType("text/html;charset=UTF-8");  
  5.           
  6.         Map map = new HashMap();  
  7.         FileItemFactory factory = new DiskFileItemFactory();  
  8.         ServletFileUpload upload = new ServletFileUpload(factory);  
  9.         File directory = null;    
  10.         List<FileItem> items = new ArrayList();  
  11.         try {  
  12.             items = upload.parseRequest(request);  
  13.             // 得到所有的文件  
  14.             Iterator<FileItem> it = items.iterator();  
  15.             while (it.hasNext()) {  
  16.                 FileItem fItem = (FileItem) it.next();  
  17.                 String fName = "";  
  18.                 Object fValue = null;  
  19.                 if (fItem.isFormField()) { // 普通文本框的值  
  20.                     fName = fItem.getFieldName();  
  21. //                  fValue = fItem.getString();  
  22.                     fValue = fItem.getString("UTF-8");  
  23.                     map.put(fName, fValue);  
  24.                 } else { // 获取上传文件的值  
  25.                     fName = fItem.getFieldName();  
  26.                     fValue = fItem.getInputStream();  
  27.                     map.put(fName, fValue);  
  28.                     String name = fItem.getName();  
  29.                     if(name != null && !("".equals(name))) {  
  30.                         name = name.substring(name.lastIndexOf(File.separator) + 1);  
  31.                           
  32. //                      String stamp = StringUtils.getFormattedCurrDateNumberString();  
  33.                         String timestamp_Str = TimeUtils.getCurrYearYYYY();  
  34.                         directory = new File("d://test");    
  35.                              directory.mkdirs();  
  36.                           
  37.                         String filePath = ("d://test")+ timestamp_Str+ File.separator + name;  
  38.                         map.put(fName + "FilePath", filePath);  
  39.                           
  40.                         InputStream is = fItem.getInputStream();  
  41.                         FileOutputStream fos = new FileOutputStream(filePath);  
  42.                         byte[] buffer = new byte[1024];  
  43.                         while (is.read(buffer) > 0) {  
  44.                             fos.write(buffer, 0, buffer.length);  
  45.                         }  
  46.                         fos.flush();  
  47.                         fos.close();  
  48.                         map.put(fName + "FileName", name);  
  49.                     }  
  50.                 }  
  51.             }  
  52.         } catch (Exception e) {  
  53.             System.out.println("读取http请求属性值出错!");  
  54. //          e.printStackTrace();  
  55.             logger.error("读取http请求属性值出错");  
  56.         }  
  57.           
  58.         // 数据处理  
  59.           
  60.           
  61.           
  62.           
  63.         try {  
  64.             out = response.getWriter();  
  65.             out.print("{success:true, msg:'接收成功'}");  
  66.             out.close();  
  67.         } catch (IOException e) {  
  68.             e.printStackTrace();  
  69.         }  
  70.   
  71.   
  72.     }  



http://blog.csdn.net/Just_szl/article/details/7659347

posted @ 2016-08-08 10:47  剑握在手  阅读(1988)  评论(0编辑  收藏  举报
返回顶部↑