使用HttpClient通过Post上传文件

阅读更多
import java.io.ByteArrayOutputStream;  
import java.io.File;  
import java.io.IOException;  
import java.io.InputStream;  
import org.apache.http.HttpEntity;  
import org.apache.http.HttpResponse;  
import org.apache.http.HttpStatus;  
import org.apache.http.ParseException;  
import org.apache.http.client.HttpClient;  
import org.apache.http.client.methods.HttpPost;  
import org.apache.http.entity.mime.MultipartEntity;  
import org.apache.http.entity.mime.content.FileBody;  
import org.apache.http.impl.client.DefaultHttpClient;  
import org.apache.http.util.EntityUtils;  
  
/** 
 *  
 * @author  Geray 
 * @version 1.0,2012-6-12  
 */  
public class HttpPostArgumentTest2 {  
  
    //file1与file2在同一个文件夹下 filepath是该文件夹指定的路径      
    public void SubmitPost(String url,String filename1,String filename2, String filepath){  
          
        HttpClient httpclient = new DefaultHttpClient();  
          
        try {  
      
            HttpPost httppost = new HttpPost(url);  
              
            FileBody bin = new FileBody(new File(filepath + File.separator + filename1));  
                
            FileBody bin2 = new FileBody(new File(filepath + File.separator + filename2));  
              
            StringBody comment = new StringBody(filename1);  
  
            MultipartEntity reqEntity = new MultipartEntity();  
              
            reqEntity.addPart("file1", bin);//file1为请求后台的File upload;属性      
             reqEntity.addPart("file2", bin2);//file2为请求后台的File upload;属性  
             reqEntity.addPart("filename1", comment);//filename1为请求后台的普通参数;属性     
            httppost.setEntity(reqEntity);  
              
            HttpResponse response = httpclient.execute(httppost);  
              
                  
            int statusCode = response.getStatusLine().getStatusCode();  
              
                  
            if(statusCode == HttpStatus.SC_OK){  
                      
                System.out.println("服务器正常响应.....");  
                  
                HttpEntity resEntity = response.getEntity();  
                  
                  
                System.out.println(EntityUtils.toString(resEntity));//httpclient自带的工具类读取返回数据  
                  
                  
                  
                System.out.println(resEntity.getContent());     
  
                EntityUtils.consume(resEntity);  
            }  
                  
            } catch (ParseException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            } finally {  
                try {   
                    httpclient.getConnectionManager().shutdown();   
                } catch (Exception ignore) {  
                      
                }  
            }  
        }  
      
      
    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
          
        HttpPostArgumentTest2 httpPostArgumentTest2 = new HttpPostArgumentTest2();  
          
        httpPostArgumentTest2.SubmitPost("http://127.0.0.1:8080/demo/receiveFileServlet",  
                "test.xml","test.zip","D://test");  
    }  
      
}  

服务端代码

public class ReceiveFileServlet extends HttpServlet  {
	private File zipFile;  
	 public void doGet(HttpServletRequest request, HttpServletResponse response)    
	            throws IOException, ServletException {
		 	String number=request.getParameter("number"); 
	      
	        System.out.println("=====type========:"+number);  
		 	PrintWriter out = null;  
	        response.setContentType("text/html;charset=UTF-8");  
	        Map map = new HashMap();  
	        FileItemFactory factory = new DiskFileItemFactory();  
	        ServletFileUpload upload = new ServletFileUpload(factory);  
	        File directory = null;    
	        List items = new ArrayList();
	        try {  
	            items = upload.parseRequest(request);  
	            // 得到所有的文件  	            
	            Iterator it = items.iterator();  
	            while (it.hasNext()) {  
	                FileItem fItem = (FileItem) it.next();  
	                String fName = "";  
	                Object fValue = null;  
	                if (fItem.isFormField()) { // 普通文本框的值  
	                    fName = fItem.getFieldName();  
//	                    fValue = fItem.getString();  
	                    fValue = fItem.getString("UTF-8");  
	                    map.put(fName, fValue);  
	                } else { // 获取上传文件的值  
	                    fName = fItem.getFieldName();  
	                    fValue = fItem.getInputStream();
	                    map.put(fName, fValue);  
	                    String name = fItem.getName(); 
	                    if(name != null && !("".equals(name))) {  
	                        name = name.substring(name.lastIndexOf(File.separator) + 1);  
	                          
	                      // String stamp = StringUtils.getFormattedCurrDateNumberString();  
	                   //    String timestamp_Str = "2013"; 
	                        directory = new File("D://receipt/test/");    
	                             directory.mkdirs();  
	                          
	                        String filePath = ("D://receipt/test/")+ File.separator + name;  
	                        map.put(fName + "FilePath", filePath);  
	                          
	                        InputStream is = fItem.getInputStream();  
	                        FileOutputStream fos = new FileOutputStream(filePath);  
	                        byte[] buffer = new byte[1024];  
	                        while (is.read(buffer) > 0) {  
	                            fos.write(buffer, 0, buffer.length);  
	                        }  
	                        fos.flush();  
	                        fos.close();  
	                        map.put(fName + "FileName", name);  
	                    }  
	                }  
	            }  
	        } catch (Exception e) {  
	            System.out.println("读取http请求属性值出错!" + e.getMessage());  
//	          e.printStackTrace();  
	            System.out.println("读取http请求属性值出错");  
	        }   
	          
	        try {  
	            out = response.getWriter();  
	            out.print("1");
	       //     out.print("{success:true, msg:'接收成功'}");  
	            out.close();  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        } 
	    }    
	   
	    public void doPost(HttpServletRequest request, HttpServletResponse response)    
	            throws IOException, ServletException {    
	        this.doGet(request, response);    
	    }  
 

 

你可能感兴趣的:(使用HttpClient通过Post上传文件)