• 利用HttpClient以post形式上传文件


    利用HttpClient以post形式上传文件

    /**
     * created since 2012-4-6
     */
    package com.yonge.http;
    
    import java.io.File;
    
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.httpclient.methods.multipart.FilePart;
    import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
    import org.apache.commons.httpclient.methods.multipart.Part;
    
    /**
     * @author wb-gaoy
     * @version $Id: HttpClientTest.java,v 0.1 2012-4-6 下午1:38:53 wb-gaoy Exp $
     */
    public class HttpClientUploadFileTest {
    
        public void uploadFile(File file, String url) {
            if (!file.exists()) {
                return;
            }
            PostMethod postMethod = new PostMethod(url);
            try {
                //FilePart:用来上传文件的类
            FilePart fp = new FilePart("filedata", file);
                Part[] parts = { fp };
    
                //对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装
                MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
                postMethod.setRequestEntity(mre);
                HttpClient client = new HttpClient();
                client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);// 设置连接时间
                int status = client.executeMethod(postMethod);
                if (status == HttpStatus.SC_OK) {
                    System.out.println(postMethod.getResponseBodyAsString());
                } else {
                    System.out.println("fail");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //释放连接
                postMethod.releaseConnection();
            }
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            HttpClientUploadFileTest test = new HttpClientUploadFileTest();
            test.uploadFile(new File("e:/default.css"),
                "http://ecmng.local.sit.alipay.net/receiveDevZipFile.json?summary=1010100");
        }
    
    }
    import java.io.File;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.methods.MultipartPostMethod;
    import org.apache.commons.httpclient.methods.multipart.FilePart;
    import org.apache.http.entity.mime.content.ContentBody;
    import org.json.JSONArray;
    import org.json.JSONObject;
    
    public class test5 {
    
      public static void main(String[] args) throws Exception {
        MultipartPostMethod filePost = new MultipartPostMethod("http://XXX.XXX.XXX.XXX:8088/XXX");
        FilePart cbFile = new FilePart("upload", new File("D:/test123.jpg"));
        cbFile.setContentType("image/*");
        filePost.addParameter("cmd_no", "2");
        //filePost.addParameter("upload", new File("D:/a.png"));
        filePost.addPart(cbFile);
        filePost.addParameter("pagesize","10");
        filePost.addParameter("pageno","1");
        HttpClient client = new HttpClient();
        // 由于要上传的文件可能比较大 , 因此在此设置最大的连接超时时间
        //client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int statusInt = client.executeMethod(filePost);
        System.out.println(statusInt);
      }
    }

     模拟端:

    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 <a href="mailto:just_szl@hotmail.com"> Geray</a>
     * @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/receiveData.do",
                    "test.xml","test.zip","D://test");
        }
        
    }

    服务器:

    public void receiveData(HttpServletRequest request, HttpServletResponse response) throws AppException{
    
            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<FileItem> items = new ArrayList();
            try {
                items = upload.parseRequest(request);
                // 得到所有的文件
                Iterator<FileItem> 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 = TimeUtils.getCurrYearYYYY();
                            directory = new File("d://test");  
                                    directory.mkdirs();
                            
                            String filePath = ("d://test")+ timestamp_Str+ 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.printStackTrace();
                logger.error("读取http请求属性值出错");
            }
            
            // 数据处理
            
            
            
            
            try {
                out = response.getWriter();
                out.print("{success:true, msg:'接收成功'}");
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
    
        }
  • 相关阅读:
    LeetCode 282. Expression Add Operators (Hard,递归分治)
    LeetCode 279. Perfect Squares
    LeetCode 278. First Bad Version
    LeetCode 275. H-Index II
    工作笔记——使用Jest时遇到的一些问题
    RFC2616-HTTP1.1-Header Field Definitions(头字段规定部分—译文)
    RFC2616-HTTP1.1-Status Code(状态码规定部分—译文)
    RFC2616-HTTP1.1-Methods(方法规定部分—译文)
    RFC2616-HTTP1.1-Status Code(状态码规定部分—单词注释版)
    RFC2616-HTTP1.1-Methods(方法规定部分—单词注释版)
  • 原文地址:https://www.cnblogs.com/blogsme/p/3016696.html
Copyright © 2020-2023  润新知