webDav之jackrabbit-webdav基礎操作

使用 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說明

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章