当前位置: 首页 > 工具软件 > WebDAV.NET > 使用案例 >

Jackrabbit-webdav 开发webdev

申屠浩歌
2023-12-01

最近由于客户提供了一个webdev的存储希望通过该存储进行文件的上传和下载,最近调研了下Jackrabbit-webdav调用nextcloud提供的服务,发现apache网站也没有给出明确的调用example,而网上大部分的example是基于1.6.5的,结合github上源码的tests内容加上自己的实践,简单的总结了一个jackrabbit-webdav-2.18.3的调用例子,供有需要的同学参考。

添加依赖包

        <dependency>
            <groupId>org.apache.jackrabbit</groupId>
            <artifactId>jackrabbit-webdav</artifactId>
            <version>2.18.3</version>
        </dependency>
package web;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
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.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.jackrabbit.webdav.DavConstants;
import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.MultiStatus;
import org.apache.jackrabbit.webdav.MultiStatusResponse;
import org.apache.jackrabbit.webdav.client.methods.HttpMkcol;
import org.apache.jackrabbit.webdav.client.methods.HttpPropfind;
import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
import org.apache.jackrabbit.webdav.version.DeltaVConstants;
import org.apache.log4j.Logger;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URLDecoder;

/**
 * @Author kailong.sun
 * @Date 2022/10/18 20:17
 * @Version 1.0
 **/
public class WebDavJackRabbitUtil {
    private static Logger logger = Logger.getLogger(WebDavJackRabbitUtil.class);

    private String username, password;
    private URI uri;
    private String root;
    private HttpClient client;
    private HttpClientContext context;

    public WebDavJackRabbitUtil(String baseUri, String userName, String passWord) {
        this.uri = URI.create(baseUri);
        this.root = this.uri.toASCIIString();
        if (!this.root.endsWith("/")) {
            this.root += "/";
        }
        this.username = userName;
        this.password = passWord;

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort());

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials upc = new UsernamePasswordCredentials(this.username, this.password);
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), upc);

        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        // Add AuthCache to the execution context
        this.context = HttpClientContext.create();
        this.context.setCredentialsProvider(credsProvider);
        this.context.setAuthCache(authCache);
        this.client = HttpClients.custom().setConnectionManager(cm).build();

    }

    public void delete(String uri) throws IOException {
        HttpDelete delete = new HttpDelete(uri);
        int status = this.client.execute(delete, this.context).getStatusLine().getStatusCode();
        logger.info("Delete " + uri + " status is :" + status);
    }

    public void upload(String uri, FileInputStream fis) throws IOException {
        HttpPut put = new HttpPut(uri);
        InputStreamEntity requestEntity = new InputStreamEntity(fis);
        put.setEntity(requestEntity);
        int status = this.client.execute(put, this.context).getStatusLine().getStatusCode();
        logger.info("Upload " + uri + " status is :" + status);
    }

    public void mkdir(String uri) throws IOException {
        HttpMkcol mkcol = new HttpMkcol(uri);
        int status = this.client.execute(mkcol, this.context).getStatusLine().getStatusCode();
        logger.info("Create folder " + uri + " status is :" + status);
    }

    public void download(String uri,String fileName) throws IOException {
        HttpGet get = new HttpGet(uri);
        HttpResponse execRel = this.client.execute(get, this.context);
        StatusLine status = execRel.getStatusLine();
        HttpEntity resp = execRel.getEntity();
        transStream2File(resp.getContent(), "C:\\Users\\amoro\\Desktop\\image"+fileName);
        logger.info("Download " + uri + " status is :" + status);
    }

    public static void main(String[] args) throws IOException {
        String url="http://158.221.136.226:8080/魔拾图片/NEO/";
        String userName ="webdav";
        String password ="moshi1212";
        WebDavJackRabbitUtil  util = new  WebDavJackRabbitUtil(url,userName,password);
        //util.download("http://158.221.136.226:8080/%e9%ad%94%e6%8b%be%e5%9b%be%e7%89%87/NEO/AW4594.jpg");
        MultiStatusResponse[] propfind = util.propfind(url);
        for (int i =1;i<propfind.length-1;i++){
            String href = propfind[i].getHref();
            String path = URLDecoder.decode(href,"UTF-8");
            util.download("http://158.221.136.226:8080/"+href,path);
        }
    }

    public MultiStatusResponse[] propfind(String testuri) throws IOException {
        MultiStatusResponse[] responses = null;
        try {
            DavPropertyNameSet names = new DavPropertyNameSet();
            names.add(DeltaVConstants.COMMENT);
            // DavConstants.DEPTH_1
            HttpPropfind propfind = new HttpPropfind(testuri, DavConstants.PROPFIND_ALL_PROP_INCLUDE, names, DavConstants.DEPTH_1);
            HttpResponse resp = this.client.execute(propfind, this.context);
            int status = resp.getStatusLine().getStatusCode();
            logger.info("List file " + uri + " status is :" + status);
            // assertEquals(207, status);
            MultiStatus multistatus;
            multistatus = propfind.getResponseBodyAsMultiStatus(resp);
            responses = multistatus.getResponses();
        } catch (DavException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return responses;
    }

    public void transStream2File(InputStream is, String fileName) throws IOException {
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        in = new BufferedInputStream(is);
        out = new BufferedOutputStream(new FileOutputStream(fileName));
        int len = -1;
        byte[] b = new byte[1024];
        while ((len = in.read(b)) != -1) {
            out.write(b, 0, len);
        }
        in.close();
        out.close();
    }
}

 类似资料: