下面列出了org.springframework.http.MediaType#APPLICATION_OCTET_STREAM 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private MediaType getContentType(String contentType) {
if (contentType.equalsIgnoreCase(MediaType.IMAGE_GIF_VALUE)) {
return MediaType.IMAGE_GIF;
} else if (contentType.equalsIgnoreCase(MediaType.IMAGE_PNG_VALUE)) {
return MediaType.IMAGE_PNG;
} else if (contentType.equalsIgnoreCase(MediaType.IMAGE_JPEG_VALUE)) {
return MediaType.IMAGE_JPEG;
} else if (contentType.equalsIgnoreCase(MediaType.TEXT_PLAIN_VALUE)) {
return MediaType.TEXT_PLAIN;
} else if (contentType.equalsIgnoreCase(MediaType.TEXT_XML_VALUE)) {
return MediaType.TEXT_XML;
} else if (contentType.equalsIgnoreCase(MediaType.TEXT_HTML_VALUE)) {
return MediaType.TEXT_HTML;
}
return MediaType.APPLICATION_OCTET_STREAM;
}
/**
* Get the media type of an image based on its extension. Supported types
* are JPEG, PNG and GIF. If there is no match based on the extension,
* MediaType.APPLICATION_OCTET_STREAM is returned.
*
* @param imageName an image name
* @return the media type of the image
*/
MediaType getMediaTypeFromImageName(String imageName) {
MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
String fileExtension = FilenameUtils.getExtension(imageName).toLowerCase();
switch (fileExtension) {
case "jpeg":
case "jpg":
mediaType = MediaType.IMAGE_JPEG;
break;
case "png":
mediaType = MediaType.IMAGE_PNG;
break;
case "gif":
mediaType = MediaType.IMAGE_GIF;
break;
}
return mediaType;
}
public static ResponseEntity<Object> export(File file) {
if (!file.exists()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("404 FILE NOT FOUND");
}
MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.setContentDispositionFormData("attachment", URLUtil.encode(file.getName()));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.add("Last-Modified", new Date().toString());
headers.add("ETag", String.valueOf(System.currentTimeMillis()));
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.length())
.contentType(mediaType)
.body(new FileSystemResource(file));
}
@Override
@SuppressWarnings("unchecked")
protected MediaType getDefaultContentType(Object object) {
if (jafPresent) {
if (object instanceof ResourceRegion) {
return ActivationMediaTypeFactory.getMediaType(((ResourceRegion) object).getResource());
}
else {
Collection<ResourceRegion> regions = (Collection<ResourceRegion>) object;
if (!regions.isEmpty()) {
return ActivationMediaTypeFactory.getMediaType(regions.iterator().next().getResource());
}
}
}
return MediaType.APPLICATION_OCTET_STREAM;
}
@Override
public boolean match(HttpRequest request) {
if (expressions.isEmpty()) {
return true;
}
HttpHeaders httpHeaders = request.getHeaders();
MediaType contentType = httpHeaders.getContentType();
if (contentType == null) {
contentType = MediaType.APPLICATION_OCTET_STREAM;
}
for (ConsumeMediaTypeExpression expression : expressions) {
if (!expression.match(contentType)) {
return false;
}
}
return true;
}
private MediaType getFileType(String fileName) {
if (fileName.endsWith(".vsix")) {
return MediaType.APPLICATION_OCTET_STREAM;
}
var contentType = URLConnection.guessContentTypeFromName(fileName);
if (contentType != null) {
return MediaType.parseMediaType(contentType);
}
return MediaType.TEXT_PLAIN;
}
private MediaType getFileType(String fileName) {
if (fileName.endsWith(".vsix")) {
return MediaType.APPLICATION_OCTET_STREAM;
}
var contentType = URLConnection.guessContentTypeFromName(fileName);
if (contentType != null) {
return MediaType.parseMediaType(contentType);
}
return MediaType.TEXT_PLAIN;
}
@Override
protected boolean matchMediaType(ServerWebExchange exchange) throws UnsupportedMediaTypeStatusException {
try {
MediaType contentType = exchange.getRequest().getHeaders().getContentType();
contentType = (contentType != null ? contentType : MediaType.APPLICATION_OCTET_STREAM);
return getMediaType().includes(contentType);
}
catch (InvalidMediaTypeException ex) {
throw new UnsupportedMediaTypeStatusException("Can't parse Content-Type [" +
exchange.getRequest().getHeaders().getFirst("Content-Type") +
"]: " + ex.getMessage());
}
}
protected MediaType getMediaType(ServletServerHttpRequest inputMessage){
MediaType contentType;
try {
contentType = inputMessage.getHeaders().getContentType();
}
catch (InvalidMediaTypeException ex) {
throw new BaseException(ex.getMessage());
}
if (contentType == null) {
contentType = MediaType.APPLICATION_OCTET_STREAM;
}
return contentType;
}
@GetMapping(value="/**")
public ResponseEntity<InputStreamResource> read(WebRequest webRequest, HttpServletRequest request, HttpServletResponse response){
String accessablePath = RequestUtils.getServletPath(request);
if(accessablePath.length()>CONTROLLER_PATH.length()){
accessablePath = accessablePath.substring(CONTROLLER_PATH.length());
}else{
throw new BaseException("error path: " + accessablePath);
}
String ext = FileUtils.getExtendName(accessablePath).toLowerCase();
MediaType mediaType = null;
if(imagePostfix.contains(ext)){
mediaType = MediaType.parseMediaType("image/"+ext);
}else{
mediaType = MediaType.APPLICATION_OCTET_STREAM;
}
if(webRequest.checkNotModified(fileStorer.getLastModified(accessablePath))){
return ResponseEntity.status(HttpStatus.NOT_MODIFIED)
.build();
}
return ResponseEntity.ok()
.contentType(mediaType)
//一起写才起作用
.cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
.lastModified(new Date().getTime())
.eTag(accessablePath)
.body(new InputStreamResource(fileStorer.readFileStream(accessablePath)));
}
public static ResponseEntity<Object> export(File file, String fileName) {
if (!file.exists()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("404 FILE NOT FOUND");
}
MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
if (StringUtils.isNullOrEmpty(fileName)) {
fileName = file.getName();
}
headers.setContentDispositionFormData("attachment", URLUtil.encode(fileName));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.add("Last-Modified", new Date().toString());
headers.add("ETag", String.valueOf(System.currentTimeMillis()));
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.length())
.contentType(mediaType)
.body(new FileSystemResource(file));
}
public static MediaType getMediaTypeForFileName(ServletContext servletContext, String fileName) {
// application/pdf
// application/xml
// image/gif, ...
String mineType = servletContext.getMimeType(fileName);
try {
MediaType mediaType = MediaType.parseMediaType(mineType);
return mediaType;
} catch (Exception e) {
return MediaType.APPLICATION_OCTET_STREAM;
}
}
public HttpMessageConverterHolder resolve(HttpRequest request,
Class<?> parameterType) {
HttpMessageConverterHolder httpMessageConverterHolder = null;
HttpHeaders httpHeaders = request.getHeaders();
MediaType contentType = httpHeaders.getContentType();
if (contentType == null) {
contentType = MediaType.APPLICATION_OCTET_STREAM;
}
for (HttpMessageConverter<?> converter : this.messageConverters) {
if (converter instanceof GenericHttpMessageConverter) {
GenericHttpMessageConverter genericConverter = (GenericHttpMessageConverter) converter;
if (genericConverter.canRead(parameterType, parameterType, contentType)) {
httpMessageConverterHolder = new HttpMessageConverterHolder(
contentType, converter);
break;
}
}
else {
if (converter.canRead(parameterType, contentType)) {
httpMessageConverterHolder = new HttpMessageConverterHolder(
contentType, converter);
break;
}
}
}
return httpMessageConverterHolder;
}
@Override
protected boolean matchMediaType(HttpServletRequest request) throws HttpMediaTypeNotSupportedException {
try {
MediaType contentType = StringUtils.hasLength(request.getContentType()) ?
MediaType.parseMediaType(request.getContentType()) :
MediaType.APPLICATION_OCTET_STREAM;
return getMediaType().includes(contentType);
}
catch (InvalidMediaTypeException ex) {
throw new HttpMediaTypeNotSupportedException(
"Can't parse Content-Type [" + request.getContentType() + "]: " + ex.getMessage());
}
}
/**
* Select the best media type for the current request through a content negotiation algorithm.
* @param exchange the current request
* @param producibleTypesSupplier the media types that can be produced for the current request
* @return the selected media type, or {@code null} if none
*/
@Nullable
protected MediaType selectMediaType(
ServerWebExchange exchange, Supplier<List<MediaType>> producibleTypesSupplier) {
MediaType contentType = exchange.getResponse().getHeaders().getContentType();
if (contentType != null && contentType.isConcrete()) {
if (logger.isDebugEnabled()) {
logger.debug(exchange.getLogPrefix() + "Found 'Content-Type:" + contentType + "' in response");
}
return contentType;
}
List<MediaType> acceptableTypes = getAcceptableTypes(exchange);
List<MediaType> producibleTypes = getProducibleTypes(exchange, producibleTypesSupplier);
Set<MediaType> compatibleMediaTypes = new LinkedHashSet<>();
for (MediaType acceptable : acceptableTypes) {
for (MediaType producible : producibleTypes) {
if (acceptable.isCompatibleWith(producible)) {
compatibleMediaTypes.add(selectMoreSpecificMediaType(acceptable, producible));
}
}
}
List<MediaType> result = new ArrayList<>(compatibleMediaTypes);
MediaType.sortBySpecificityAndQuality(result);
MediaType selected = null;
for (MediaType mediaType : result) {
if (mediaType.isConcrete()) {
selected = mediaType;
break;
}
else if (mediaType.isPresentIn(ALL_APPLICATION_MEDIA_TYPES)) {
selected = MediaType.APPLICATION_OCTET_STREAM;
break;
}
}
if (selected != null) {
if (logger.isDebugEnabled()) {
logger.debug("Using '" + selected + "' given " + acceptableTypes +
" and supported " + producibleTypes);
}
}
else if (logger.isDebugEnabled()) {
logger.debug(exchange.getLogPrefix() +
"No match for " + acceptableTypes + ", supported: " + producibleTypes);
}
return selected;
}
private Publisher<?> body(Object handler, ServerWebExchange exchange) {
ResolvableType elementType = ResolvableType
.forClass(this.inspector.getInputType(handler));
// we effectively delegate type conversion to FunctionCatalog
elementType = ResolvableType.forClass(String.class);
ResolvableType actualType = elementType;
Class<?> resolvedType = elementType.resolve();
ReactiveAdapter adapter = (resolvedType != null
? getAdapterRegistry().getAdapter(resolvedType) : null);
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
MediaType contentType = request.getHeaders().getContentType();
MediaType mediaType = (contentType != null ? contentType
: MediaType.APPLICATION_OCTET_STREAM);
if (logger.isDebugEnabled()) {
logger.debug(exchange.getLogPrefix() + (contentType != null
? "Content-Type:" + contentType
: "No Content-Type, using " + MediaType.APPLICATION_OCTET_STREAM));
}
boolean isBodyRequired = (adapter != null && !adapter.supportsEmpty());
MethodParameter bodyParam = new MethodParameter(handlerMethod(handler), 0);
for (HttpMessageReader<?> reader : getMessageReaders()) {
if (reader.canRead(elementType, mediaType)) {
Map<String, Object> readHints = Hints.from(Hints.LOG_PREFIX_HINT,
exchange.getLogPrefix());
if (adapter != null && adapter.isMultiValue()) {
if (logger.isDebugEnabled()) {
logger.debug(
exchange.getLogPrefix() + "0..N [" + elementType + "]");
}
Flux<?> flux = reader.read(actualType, elementType, request, response,
readHints);
flux = flux.onErrorResume(
ex -> Flux.error(handleReadError(bodyParam, ex)));
if (isBodyRequired) {
flux = flux.switchIfEmpty(
Flux.error(() -> handleMissingBody(bodyParam)));
}
return Mono.just(adapter.fromPublisher(flux));
}
else {
// Single-value (with or without reactive type wrapper)
if (logger.isDebugEnabled()) {
logger.debug(exchange.getLogPrefix() + "0..1 [" + elementType + "]");
}
Mono<?> mono = reader.readMono(actualType, elementType, request,
response, readHints).doOnNext(v -> {
if (logger.isDebugEnabled()) {
logger.debug("received: " + v);
}
});
mono = mono.onErrorResume(
ex -> Mono.error(handleReadError(bodyParam, ex)));
if (isBodyRequired) {
mono = mono.switchIfEmpty(
Mono.error(() -> handleMissingBody(bodyParam)));
}
return (adapter != null ? Mono.just(adapter.fromPublisher(mono))
: Mono.from(mono));
}
}
}
return Mono.error(new UnsupportedMediaTypeStatusException(mediaType,
Arrays.asList(MediaType.APPLICATION_JSON), elementType));
}
/**
* Writes the given return type to the given output message.
* @param returnValue the value to write to the output message
* @param returnType the type of the value
* @param inputMessage the input messages. Used to inspect the {@code Accept} header.
* @param outputMessage the output message to write to
* @throws IOException thrown in case of I/O errors
* @throws HttpMediaTypeNotAcceptableException thrown when the conditions indicated by {@code Accept} header on
* the request cannot be met by the message converters
*/
@SuppressWarnings("unchecked")
protected <T> void writeWithMessageConverters(T returnValue, MethodParameter returnType,
ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage)
throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {
Class<?> returnValueClass = getReturnValueType(returnValue, returnType);
Type returnValueType = getGenericType(returnType);
HttpServletRequest servletRequest = inputMessage.getServletRequest();
List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(servletRequest);
List<MediaType> producibleMediaTypes = getProducibleMediaTypes(servletRequest, returnValueClass, returnValueType);
if (returnValue != null && producibleMediaTypes.isEmpty()) {
throw new IllegalArgumentException("No converter found for return value of type: " + returnValueClass);
}
Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>();
for (MediaType requestedType : requestedMediaTypes) {
for (MediaType producibleType : producibleMediaTypes) {
if (requestedType.isCompatibleWith(producibleType)) {
compatibleMediaTypes.add(getMostSpecificMediaType(requestedType, producibleType));
}
}
}
if (compatibleMediaTypes.isEmpty()) {
if (returnValue != null) {
throw new HttpMediaTypeNotAcceptableException(producibleMediaTypes);
}
return;
}
List<MediaType> mediaTypes = new ArrayList<MediaType>(compatibleMediaTypes);
MediaType.sortBySpecificityAndQuality(mediaTypes);
MediaType selectedMediaType = null;
for (MediaType mediaType : mediaTypes) {
if (mediaType.isConcrete()) {
selectedMediaType = mediaType;
break;
}
else if (mediaType.equals(MediaType.ALL) || mediaType.equals(MEDIA_TYPE_APPLICATION)) {
selectedMediaType = MediaType.APPLICATION_OCTET_STREAM;
break;
}
}
if (selectedMediaType != null) {
selectedMediaType = selectedMediaType.removeQualityValue();
for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
if (messageConverter instanceof GenericHttpMessageConverter) {
if (((GenericHttpMessageConverter<T>) messageConverter).canWrite(returnValueType,
returnValueClass, selectedMediaType)) {
returnValue = (T) getAdvice().beforeBodyWrite(returnValue, returnType, selectedMediaType,
(Class<? extends HttpMessageConverter<?>>) messageConverter.getClass(),
inputMessage, outputMessage);
if (returnValue != null) {
addContentDispositionHeader(inputMessage, outputMessage);
((GenericHttpMessageConverter<T>) messageConverter).write(returnValue,
returnValueType, selectedMediaType, outputMessage);
if (logger.isDebugEnabled()) {
logger.debug("Written [" + returnValue + "] as \"" +
selectedMediaType + "\" using [" + messageConverter + "]");
}
}
return;
}
}
else if (messageConverter.canWrite(returnValueClass, selectedMediaType)) {
returnValue = (T) getAdvice().beforeBodyWrite(returnValue, returnType, selectedMediaType,
(Class<? extends HttpMessageConverter<?>>) messageConverter.getClass(),
inputMessage, outputMessage);
if (returnValue != null) {
addContentDispositionHeader(inputMessage, outputMessage);
((HttpMessageConverter<T>) messageConverter).write(returnValue,
selectedMediaType, outputMessage);
if (logger.isDebugEnabled()) {
logger.debug("Written [" + returnValue + "] as \"" +
selectedMediaType + "\" using [" + messageConverter + "]");
}
}
return;
}
}
}
if (returnValue != null) {
throw new HttpMediaTypeNotAcceptableException(this.allSupportedMediaTypes);
}
}
/**
* Read the body from a method argument with {@link HttpMessageReader}.
* @param bodyParam represents the element type for the body
* @param actualParam the actual method argument type; possibly different
* from {@code bodyParam}, e.g. for an {@code HttpEntity} argument
* @param isBodyRequired true if the body is required
* @param bindingContext the binding context to use
* @param exchange the current exchange
* @return a Mono with the value to use for the method argument
* @since 5.0.2
*/
protected Mono<Object> readBody(MethodParameter bodyParam, @Nullable MethodParameter actualParam,
boolean isBodyRequired, BindingContext bindingContext, ServerWebExchange exchange) {
ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParam);
ResolvableType actualType = (actualParam != null ? ResolvableType.forMethodParameter(actualParam) : bodyType);
Class<?> resolvedType = bodyType.resolve();
ReactiveAdapter adapter = (resolvedType != null ? getAdapterRegistry().getAdapter(resolvedType) : null);
ResolvableType elementType = (adapter != null ? bodyType.getGeneric() : bodyType);
isBodyRequired = isBodyRequired || (adapter != null && !adapter.supportsEmpty());
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
MediaType contentType = request.getHeaders().getContentType();
MediaType mediaType = (contentType != null ? contentType : MediaType.APPLICATION_OCTET_STREAM);
Object[] hints = extractValidationHints(bodyParam);
if (logger.isDebugEnabled()) {
logger.debug(exchange.getLogPrefix() + (contentType != null ?
"Content-Type:" + contentType :
"No Content-Type, using " + MediaType.APPLICATION_OCTET_STREAM));
}
for (HttpMessageReader<?> reader : getMessageReaders()) {
if (reader.canRead(elementType, mediaType)) {
Map<String, Object> readHints = Hints.from(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix());
if (adapter != null && adapter.isMultiValue()) {
if (logger.isDebugEnabled()) {
logger.debug(exchange.getLogPrefix() + "0..N [" + elementType + "]");
}
Flux<?> flux = reader.read(actualType, elementType, request, response, readHints);
flux = flux.onErrorResume(ex -> Flux.error(handleReadError(bodyParam, ex)));
if (isBodyRequired) {
flux = flux.switchIfEmpty(Flux.error(() -> handleMissingBody(bodyParam)));
}
if (hints != null) {
flux = flux.doOnNext(target ->
validate(target, hints, bodyParam, bindingContext, exchange));
}
return Mono.just(adapter.fromPublisher(flux));
}
else {
// Single-value (with or without reactive type wrapper)
if (logger.isDebugEnabled()) {
logger.debug(exchange.getLogPrefix() + "0..1 [" + elementType + "]");
}
Mono<?> mono = reader.readMono(actualType, elementType, request, response, readHints);
mono = mono.onErrorResume(ex -> Mono.error(handleReadError(bodyParam, ex)));
if (isBodyRequired) {
mono = mono.switchIfEmpty(Mono.error(() -> handleMissingBody(bodyParam)));
}
if (hints != null) {
mono = mono.doOnNext(target ->
validate(target, hints, bodyParam, bindingContext, exchange));
}
return (adapter != null ? Mono.just(adapter.fromPublisher(mono)) : Mono.from(mono));
}
}
}
// No compatible reader but body may be empty..
HttpMethod method = request.getMethod();
if (contentType == null && method != null && SUPPORTED_METHODS.contains(method)) {
Flux<DataBuffer> body = request.getBody().doOnNext(o -> {
// Body not empty, back to 415..
throw new UnsupportedMediaTypeStatusException(mediaType, this.supportedMediaTypes, elementType);
});
if (isBodyRequired) {
body = body.switchIfEmpty(Mono.error(() -> handleMissingBody(bodyParam)));
}
return (adapter != null ? Mono.just(adapter.fromPublisher(body)) : Mono.from(body));
}
return Mono.error(new UnsupportedMediaTypeStatusException(mediaType, this.supportedMediaTypes, elementType));
}
/**
* Create a new instance of the {@code ByteArrayHttpMessageConverter}.
*/
public ByteArrayHttpMessageConverter() {
super(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL);
}
/**
* Determine the Content-Type of the HTTP message based on the
* "Content-Type" header or otherwise default to
* {@link MediaType#APPLICATION_OCTET_STREAM}.
* @param inputMessage the HTTP message
* @return the MediaType, possibly {@code null}.
*/
@Nullable
protected MediaType getContentType(HttpMessage inputMessage) {
MediaType contentType = inputMessage.getHeaders().getContentType();
return (contentType != null ? contentType : MediaType.APPLICATION_OCTET_STREAM);
}