protected void addDefaultHeaders(HttpHeaders headers, T t, MediaType contentType) throws IOException{ if (headers.getContentType() == null) { MediaType contentTypeToUse = contentType; if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype()) { contentTypeToUse = getDefaultContentType(t); } else if (MediaType.APPLICATION_OCTET_STREAM.equals(contentType)) { MediaType mediaType = getDefaultContentType(t); contentTypeToUse = (mediaType != null ? mediaType : contentTypeToUse); } if (contentTypeToUse != null) { if (contentTypeToUse.getCharset() == null) { Charset defaultCharset = getDefaultCharset(); if (defaultCharset != null) { contentTypeToUse = new MediaType(contentTypeToUse, defaultCharset); } } headers.setContentType(contentTypeToUse); } } if (headers.getContentLength() < 0 && !headers.containsKey(HttpHeaders.TRANSFER_ENCODING)) { Long contentLength = getContentLength(t, headers.getContentType()); if (contentLength != null) { headers.setContentLength(contentLength); } } }
@Override protected MediaType getDefaultContentType(Resource resource) { if (jafPresent) { return ActivationMediaTypeFactory.getMediaType(resource); } else { return MediaType.APPLICATION_OCTET_STREAM; } }
class ActivationMediaTypeFactory { private static final FileTypeMap fileTypeMap; static { fileTypeMap = loadFileTypeMapFromContextSupportModule(); } private static FileTypeMap loadFileTypeMapFromContextSupportModule() { // See if we can find the extended mime.types from the context-support module... Resource mappingLocation = new ClassPathResource("org/springframework/mail/javamail/mime.types"); if (mappingLocation.exists()) { InputStream inputStream = null; try { inputStream = mappingLocation.getInputStream(); return new MimetypesFileTypeMap(inputStream); } catch (IOException ex) { // ignore } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ex) { // ignore } } } } return FileTypeMap.getDefaultFileTypeMap(); } public static MediaType getMediaType(Resource resource) { String filename = resource.getFilename(); if (filename != null) { String mediaType = fileTypeMap.getContentType(filename); if (StringUtils.hasText(mediaType)) { return MediaType.parseMediaType(mediaType); } } return null; } }
想獲取最新內容,請關注微信公衆號
java