`

HttpClient文件上传代码

阅读更多
摘自今天写的一段代码:

    public static int uploadFiles(String fullUrl,Map files,Map params,Map cookies,String encoding) throws IOException {
        HttpClient client = new HttpClient();
        try {
            if(encoding!=null && encoding.length()>0) {
                EncodingUtil.TempEncoding=encoding;
            }
            URL url=new URL(fullUrl);
            String host=url.getHost();
            String path=url.getPath();
            PostMethod post=new PostMethod(fullUrl);
            try {
                post.setFollowRedirects(false);
                List parts=new ArrayList();
                if(params!=null) {
                    for (Map.Entry entry : params.entrySet()) {
                        String name=entry.getKey();
                        Object val=entry.getValue();
                        if(val instanceof Collection) {
                            for (Object one : (Collection)val) {
                                parts.add(new StringPart(name,one.toString(),encoding));
                            }
                        } else if(val.getClass().isArray()) {
                            int len = Array.getLength(val);
                            for(int i=0;i entry : files.entrySet()) {
                        parts.add(new FilePart(entry.getKey(),entry.getValue()));
                    }
                }
                post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]),post.getParams()));
                if(cookies!=null) {
                    HttpState state = client.getState();
                    if(state==null) {
                        state=new HttpState();
                    }
                    for (Map.Entry entry : cookies.entrySet()) {
                        Cookie cookie=new Cookie();
                        cookie.setDomain(host);
                        cookie.setPath(path);
                        cookie.setName(entry.getKey());
                        cookie.setValue(entry.getValue());
                        state.addCookie(cookie);
                    }
                    client.setState(state);
                }
                return client.executeMethod(post);
            } finally {
                post.releaseConnection();
            }
        } finally {
            EncodingUtil.TempEncoding=null;
            client.getHttpConnectionManager().closeIdleConnections(0);
        }
    }
一个静态函数,拷贝下来就能用
参数说明:
String fullUrl :上传的地址,全路径,如 http://localhost/doupload.jsp
Map files : 要传的文件,可以是多个
Map params : 同时还可以传递参数,Object 一般是String,也可以是 String[] 或 List
Map cookies : 可能要设置的cookie值
String encoding : 文件名的编码
调用示例:

    public void test10() throws Exception {
        Map files=new HashMap();
        files.put("file1",new File("C:\\Users\\zms\\Desktop\\密保卡.jpg"));
        files.put("file2",new File("C:\\Users\\zms\\Desktop\\todo.txt"));
        Map params=new HashMap();
        params.put("key1","val1");
        params.put("key2","值2");
        params.put("键3","值3");
        Map cookies=new HashMap();
        cookies.put("JSESSIONID","BD8BE17C1E56C81DA866643E7125A163");
        int status = Tools.uploadFiles("http://localhost/doupload.jsp", files, params, cookies,"GB18030");
        System.out.println(status);
    }
注意:默认 HttpClient 是无法传中文文件名的
注意代码里的
EncodingUtil.TempEncoding=encoding;
这句是编译不过的,需要修改HttpClient的源代码
我用的版本是HttpClient 3.1,修改 org.apache.commons.httpclient.util.EncodingUtil
大概在 222行,修改 getAsciiBytes 函数,增加 一个静态变量,代码大概如:

    public static String TempEncoding="";
    /**
     * Converts the specified string to byte array of ASCII characters.
     *
     * @param data the string to be encoded
     * @return The string as a byte array.
     *
     * @since 3.0
     */
    public static byte[] getAsciiBytes(final String data) {

        if (data == null) {
            throw new IllegalArgumentException("Parameter may not be null");
        }

        try {
            return data.getBytes((TempEncoding!=null && TempEncoding.length()>0)?TempEncoding:"US-ASCII");
        } catch (UnsupportedEncodingException e) {
            throw new HttpClientError("HttpClient requires ASCII support");
        }
    }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics