webDav之jackrabbit-webdav基础操作

曹振
2023-12-01

使用 jackrabbit-webdav 实现对附件的上传下载操作

依赖的包

<dependency>
    <groupId>org.apache.jackrabbit</groupId>
    <artifactId>jackrabbit-webdav</artifactId>
    <version>2.21.1</version>
</dependency>

使用的相关类

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.util.EntityUtils;
import org.apache.jackrabbit.webdav.DavConstants;
import org.apache.jackrabbit.webdav.DavServletResponse;
import org.apache.jackrabbit.webdav.client.methods.HttpMkcol;
import org.apache.jackrabbit.webdav.client.methods.HttpPropfind;

具体操作

连接 webDav 服务
  • 初始化 HttpClient 对象

    public static HttpClient initHttpClient() {
       
        PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager();
        //设置最大连接数
        pcm.setMaxTotal(100);
        pcm.setDefaultMaxPerRoute(80);
        // 通过连接池获取 httpClient 对象
        return HttpClients.custom().setConnectionManager(pcm).build();
    }
    
  • 初始化 HttpClientContext 对象

    public static HttpClientContext initContext() {
        WebDavConfig config = WebDavConfig.getInstance();
    
        URI uri = null;
        try {
            uri = new URI(config.getBaseUrl());
        } catch (URISyntaxException e) {
            logger.error("", e);
            throw new WebDavException();
        }
        // uri 转换成 HttpHost 对象
        HttpHost target = new HttpHost(uri.getHost(), uri.getPort());
    
        // 用户名/密码认证
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(config.getUserName(), config.getPassword());
        credentialsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), credentials);
    
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicScheme = new BasicScheme();
        authCache.put(target, basicScheme);
    
        // Add AuthCache to the execution context
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credentialsProvider);
        context.setAuthCache(authCache);
    
        return context;
    }
    

    注:其中使用的 WebDavConfig 是配置登录地址、用户名、密码等相关配置类

上传附件
public static String upload(String fileName, InputStream inputStream) {
    if (null == inputStream) {
        return null;
    }

    String path = config.getBaseUrl() + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + "/";
    // 生成文件名
    String suffix = fileName.substring(fileName.lastIndexOf("."));
    String newFileName = Snowflake.getInstance().nextId() + suffix;

    HttpClient client = WebDavInitUtil.initHttpClient();
    HttpClientContext context = WebDavInitUtil.initContext();

    try {
        if (!existDir(path, client, context)) {
            // 不存在目录则创建
            mkDirs(path, client, context);
        }
        String fileUri = path + newFileName;
        HttpPut put = new HttpPut(fileUri);
        InputStreamEntity entity = new InputStreamEntity(inputStream);
        put.setEntity(entity);
        int status = client.execute(put, context).getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_OK) {
            return fileUri;
        }
    } catch (IOException e) {
        logger.error("error uploading file to webDav server.", e);
    }
    return null;
}
下载附件
public static void download2Stream(String filePath, OutputStream out) {
	// 判断是否以http开头,如果不是的话就是缺少基础的url,补全
    if (!filePath.startsWith(Constants.START_STR)) {
        filePath = config.getBaseUrl() + filePath;
    }
    HttpClient client = WebDavInitUtil.initHttpClient();
    HttpClientContext context = WebDavInitUtil.initContext();
    HttpGet get = new HttpGet(filePath);
    try {
        HttpResponse response = client.execute(get, context);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            StreamUtil.transStream(entity.getContent(), out);
            EntityUtils.consume(entity);
            return;
        }
    } catch (IOException e) {
        logger.error("Download file to OutputStream error.", e);
    }
    throw new WebDavException("Download file to OutputStream error.");
}
创建文件夹
public static Boolean mkDirs(String path, HttpClient client, HttpClientContext context) throws IOException {
    String temDir = path;
    if (path.startsWith(Constants.START_STR)) {
        temDir = path.replaceAll(config.getBaseUrl(), "");
    }
    String[] dirs = temDir.split("/");
    String uri = config.getBaseUrl();
    for (String dir : dirs) {
        uri = uri + dir + "/";
        if (existDir(uri, client, context)) {
            logger.info(uri + ",已存在");
            continue;
        }
        if (mkdir(uri, client, context) != HttpStatus.SC_CREATED) {
            return false;
        }
    }
    return true;
}
执行创建目录请求
private static Integer mkdir(String dir, HttpClient client, HttpClientContext context) throws IOException {
    HttpMkcol mkcol = new HttpMkcol(dir);
    int retCode = client.execute(mkcol, context).getStatusLine().getStatusCode();
    logger.info("创建目录" + dir + ",结果为:" + retCode);
    return retCode;
}
判断目录/文件是否存在
public static Boolean existDir(String path, HttpClient client, HttpClientContext context) throws IOException {
    if (!path.startsWith(Constants.START_STR)) {
        path = config.getBaseUrl() + path + "/";
    }
    logger.info("待判断路径:" + path);
    HttpPropfind propfind = new HttpPropfind(path, DavConstants.PROPFIND_BY_PROPERTY, 1);
    HttpResponse response = client.execute(propfind, context);
    int statusCode = response.getStatusLine().getStatusCode();

    logger.info("判断目录是否存在,返回值:" + statusCode);
    return DavServletResponse.SC_MULTI_STATUS == statusCode;
}

参考:

Jackrabbit-webdav接口调用Example

webdav 概览

webDav说明

 类似资料: