indiWiz.com

Subhash's Tech Log

WebDav Client in Java

with 2 comments

The history of Java WebDav client is discussed well in this blog: http://pragmaticchris.blogspot.com/2007/11/java-webdav-clients.html. There is one update to it though: the JackRabbit project has a well-defined WebDav client (extending Commons HTTP Client) available.

To add JackRabbit WebDav client to your Maven project, use this:

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

I will show one example of using the WebDav client which I had developed to upload content to an WebDav server:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.jackrabbit.webdav.client.methods.PutMethod;

...

// WebDAV URL:
final String baseUrl = ...;
// Source file to upload:
File f = ...;
try{
    HttpClient client = new HttpClient();
    Credentials creds = new UsernamePasswordCredentials("username", "password");
    client.getState().setCredentials(AuthScope.ANY, creds);

    PutMethod method = new PutMethod(baseUrl + "/" + f.getName());
    RequestEntity requestEntity = new InputStreamRequestEntity(
	    new FileInputStream(f));
    method.setRequestEntity(requestEntity);
    client.executeMethod(method);
    System.out.println(method.getStatusCode() + " " + method.getStatusText());
}
catch(HttpException ex){
    // Handle Exception
}
catch(IOException ex){
    // Handle Exception
}

Written by Subhash Chandran

February 11th, 2009 at 4:24 pm

Posted in Java

Tagged with , ,

2 Responses to 'WebDav Client in Java'

Subscribe to comments with RSS or TrackBack to 'WebDav Client in Java'.

  1. Good example to upload a file. Could you please share an example to import a file also. I followed Jacakrabbit webdav wiki site and could able to get only the file list. How to get each file downloaded?

    Dilip

    12 Jun 09 at 9:00 am

  2. I’ve created a new webdav client for Java that is quite a bit easier to use than jackrabbit. Basically, I’ve abstracted all the HttpClient stuff away and just expose a few easy to use methods for common use cases.

    It is called sardine and lives up on google code:

    http://code.google.com/p/sardine/

    Jon Stevens

    7 Jan 10 at 6:14 am

Leave a Reply