mardi 21 octobre 2008

How to copy a file on webdav using common-httpclient ?

Webdav technology allow sharing files with internet. WebDav is a filesytem interface relying on http protocol, a non transactionnal. Webdav manages files whithout locking and work using a versionning system in order to continue working for multiple users. A tricky mecanism for holding concurrent versions lay behind the scene, but if you plan to use WebDav like you'd use a samba filesytem, you may not care understanding of the hidden processes.

If your on a local network, you'd still prefer more standard file system for convenience.

In java, you can use the generic http client commons-httpclient to put your files on a webdav server. I give you a sample code that let you create a file on the server and then DELETE it. Somme more sophisticated operations can be performed with the jackrabbit-webdav library, it will provide you with more operations.

HostConfiguration hostConfig = new HostConfiguration();
hostConfig.setHost("targetserver");
HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
int maxHostConnections = 20;
params.setMaxConnectionsPerHost(hostConfig, maxHostConnections);
connectionManager.setParams(params);
HttpClient client = new HttpClient(connectionManager);
Credentials creds = new UsernamePasswordCredentials("username","password");
client.getState().setCredentials(AuthScope.ANY, creds);
client.setHostConfiguration(hostConfig);
PutMethod putMethod = new PutMethod(
"http://targetserver:8080/webdav/targetfilename");
FileInputStream is = new FileInputStream("myfile.pdf");
InputStreamRequestEntity requestEntity = new InputStreamRequestEntity(is);
putMethod.setRequestEntity(requestEntity);
client.executeMethod(putMethod);
System.out.println(putMethod.getStatusCode() + " "
+ putMethod.getStatusText());


You could have to sort of status code :
201 Created (A file has been created)
204 No data(The http response has no data, but the operation has performed correctly)

And to delete a file :



DeleteMethod deleteMethod = new DeleteMethod(
"http://targetserver:8080/webdav/targetfilename");
client.executeMethod(deleteMethod);
System.out.println(putMethod.getStatusCode() + " "
+ putMethod.getStatusText());

Aucun commentaire: