如何使用resttemplate进行WebDav调用?

时间:2019-01-24 19:46:29

标签: java spring resttemplate webdav

如果我试图从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();
   }

1 个答案:

答案 0 :(得分:0)

我能够使用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 

}