如何使用 resttemplate 进行 WebDav 调用?

How do I make a WebDav call using resttemplate?

如果我试图从 webdav 服务器获取文件,如何使用 resttemplate 进行 WebDav 调用。

我曾经像这样使用 HttpClient 来做到这一点:

public byte[] getFileAsBytes( String location ) throws FileNotFoundException, IOException {
      GetMethod method = new GetMethod( baseUrl + "/" + location );
      client.executeMethod( method );
      if ( method.getStatusCode() == HttpStatus.SC_NOT_FOUND ) {
         throw new FileNotFoundException( "Got error " + method.getStatusCode() + " : " + method.getStatusText()
               + " retrieving file from webdav server at path " + location );
      } else if ( method.getStatusCode() != HttpStatus.SC_OK ) {
         throw new IOException( "Got error " + method.getStatusCode() + " : " + method.getStatusText()
               + " retrieving file from webdav server at path " + location );
      }
      return method.getResponseBody();
   }

我能够使用 restTemplate 访问 WebDav 服务器,如下所示:

   /**
    * This method copies the file from webdav to local system
    *
    * @param documentMetadata
    * @return
    */
   @Override
   public Document downloadFile( DocumentMetadata documentMetadata ) {
      Document document = new Document();
      String fileUrl = baseUrl + documentMetadata.getFilepath();

      ResponseEntity<byte[]> result = restTemplate.exchange(fileUrl, HttpMethod.GET, new HttpEntity<>( createHeaders( username, password )), byte[].class );


      return document;
   }

   private Void prepareDocument( ClientHttpResponse response, Document document, DocumentMetadata meta ) throws IOException {

      document.setName( meta.getFilename() );
      document.setFilePath( meta.getFilepath() );
      document.setFile( IOUtils.toByteArray( response.getBody() ) );
      return null;
   }

   public static HttpHeaders createHeaders( final String userName, final String password ) {
      log.debug( "SlateUtil.createHeaders" );
      return new HttpHeaders(){{
         String auth = userName + ":" + password;
         byte[] encodedAuth = Base64.encodeBase64(
               auth.getBytes( Charset.forName( "US-ASCII" )));
         String authHeader = "Basic " + new String( encodedAuth );
         set( "Authorization", authHeader );
      }};
   }

供其他人参考,如果他们遇到这个问题:

这是我的模型的样子。

public class Document {
   private String name;
   private byte[] file;
   private String filePath;
   private String contentType;
// getters and setters 
}

public class DocumentMetadata {

   private String id;
   private String filename;
   private String filepath;
   private String extension;
   private String createdBy;
   private Date createDate;
   private String size;
   private String documentType;
   private String displayName;
    // getters and setters 

}