Java Code Examples for org.springframework.http.HttpHeaders#getContentType()

The following examples show how to use org.springframework.http.HttpHeaders#getContentType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PropertiesHttpMessageConverter.java    From SpringAll with MIT License 6 votes vote down vote up
@Override
protected Properties readInternal(Class<? extends Properties> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    Properties properties = new Properties();
    // 获取请求头
    HttpHeaders headers = inputMessage.getHeaders();
    // 获取 content-type
    MediaType contentType = headers.getContentType();
    // 获取编码
    Charset charset = null;
    if (contentType != null) {
        charset = contentType.getCharset();
    }

    charset = charset == null ? Charset.forName("UTF-8") : charset;

    // 获取请求体
    InputStream body = inputMessage.getBody();
    InputStreamReader inputStreamReader = new InputStreamReader(body, charset);

    properties.load(inputStreamReader);
    return properties;
}
 
Example 2
Source File: FormHttpMessageConverter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) throws IOException {
	Object partBody = partEntity.getBody();
	if (partBody == null) {
		throw new IllegalStateException("Empty body for part '" + name + "': " + partEntity);
	}
	Class<?> partType = partBody.getClass();
	HttpHeaders partHeaders = partEntity.getHeaders();
	MediaType partContentType = partHeaders.getContentType();
	for (HttpMessageConverter<?> messageConverter : this.partConverters) {
		if (messageConverter.canWrite(partType, partContentType)) {
			Charset charset = isFilenameCharsetSet() ? StandardCharsets.US_ASCII : this.charset;
			HttpOutputMessage multipartMessage = new MultipartHttpOutputMessage(os, charset);
			multipartMessage.getHeaders().setContentDispositionFormData(name, getFilename(partBody));
			if (!partHeaders.isEmpty()) {
				multipartMessage.getHeaders().putAll(partHeaders);
			}
			((HttpMessageConverter<Object>) messageConverter).write(partBody, partContentType, multipartMessage);
			return;
		}
	}
	throw new HttpMessageNotWritableException("Could not write request: no suitable HttpMessageConverter " +
			"found for request type [" + partType.getName() + "]");
}
 
Example 3
Source File: FeignMultipartEncoder.java    From hawkbit-examples with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void encodeRequest(final Object value, final HttpHeaders requestHeaders, final RequestTemplate template) {
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final HttpOutputMessage dummyRequest = new HttpOutputMessageImpl(outputStream, requestHeaders);
    try {
        final Class<?> requestType = value.getClass();
        final MediaType requestContentType = requestHeaders.getContentType();
        for (final HttpMessageConverter<?> messageConverter : converters) {
            if (messageConverter.canWrite(requestType, requestContentType)) {
                ((HttpMessageConverter<Object>) messageConverter).write(value, requestContentType, dummyRequest);
                break;
            }
        }
    } catch (final IOException ex) {
        throw new EncodeException("Cannot encode request.", ex);
    }
    final HttpHeaders headers = dummyRequest.getHeaders();
    for (final Entry<String, List<String>> entry : headers.entrySet()) {
        template.header(entry.getKey(), entry.getValue());
    }
    /*
     * we should use a template output stream... this will cause issues if
     * files are too big, since the whole request will be in memory.
     */
    template.body(outputStream.toByteArray(), UTF_8);
}
 
Example 4
Source File: FormHttpMessageConverter.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) throws IOException {
	Object partBody = partEntity.getBody();
	if (partBody == null) {
		throw new IllegalStateException("Empty body for part '" + name + "': " + partEntity);
	}
	Class<?> partType = partBody.getClass();
	HttpHeaders partHeaders = partEntity.getHeaders();
	MediaType partContentType = partHeaders.getContentType();
	for (HttpMessageConverter<?> messageConverter : this.partConverters) {
		if (messageConverter.canWrite(partType, partContentType)) {
			Charset charset = isFilenameCharsetSet() ? StandardCharsets.US_ASCII : this.charset;
			HttpOutputMessage multipartMessage = new MultipartHttpOutputMessage(os, charset);
			multipartMessage.getHeaders().setContentDispositionFormData(name, getFilename(partBody));
			if (!partHeaders.isEmpty()) {
				multipartMessage.getHeaders().putAll(partHeaders);
			}
			((HttpMessageConverter<Object>) messageConverter).write(partBody, partContentType, multipartMessage);
			return;
		}
	}
	throw new HttpMessageNotWritableException("Could not write request: no suitable HttpMessageConverter " +
			"found for request type [" + partType.getName() + "]");
}
 
Example 5
Source File: FormHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) throws IOException {
	Object partBody = partEntity.getBody();
	Class<?> partType = partBody.getClass();
	HttpHeaders partHeaders = partEntity.getHeaders();
	MediaType partContentType = partHeaders.getContentType();
	for (HttpMessageConverter<?> messageConverter : this.partConverters) {
		if (messageConverter.canWrite(partType, partContentType)) {
			HttpOutputMessage multipartMessage = new MultipartHttpOutputMessage(os);
			multipartMessage.getHeaders().setContentDispositionFormData(name, getFilename(partBody));
			if (!partHeaders.isEmpty()) {
				multipartMessage.getHeaders().putAll(partHeaders);
			}
			((HttpMessageConverter<Object>) messageConverter).write(partBody, partContentType, multipartMessage);
			return;
		}
	}
	throw new HttpMessageNotWritableException("Could not write request: no suitable HttpMessageConverter " +
			"found for request type [" + partType.getName() + "]");
}
 
Example 6
Source File: FormHttpMessageConverter.java    From java-technology-stack with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) throws IOException {
	Object partBody = partEntity.getBody();
	if (partBody == null) {
		throw new IllegalStateException("Empty body for part '" + name + "': " + partEntity);
	}
	Class<?> partType = partBody.getClass();
	HttpHeaders partHeaders = partEntity.getHeaders();
	MediaType partContentType = partHeaders.getContentType();
	for (HttpMessageConverter<?> messageConverter : this.partConverters) {
		if (messageConverter.canWrite(partType, partContentType)) {
			Charset charset = isFilenameCharsetSet() ? StandardCharsets.US_ASCII : this.charset;
			HttpOutputMessage multipartMessage = new MultipartHttpOutputMessage(os, charset);
			multipartMessage.getHeaders().setContentDispositionFormData(name, getFilename(partBody));
			if (!partHeaders.isEmpty()) {
				multipartMessage.getHeaders().putAll(partHeaders);
			}
			((HttpMessageConverter<Object>) messageConverter).write(partBody, partContentType, multipartMessage);
			return;
		}
	}
	throw new HttpMessageNotWritableException("Could not write request: no suitable HttpMessageConverter " +
			"found for request type [" + partType.getName() + "]");
}
 
Example 7
Source File: AbstractHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Add default headers to the output message.
 * <p>This implementation delegates to {@link #getDefaultContentType(Object)} if a content
 * type was not provided, calls {@link #getContentLength}, and sets the corresponding headers
 * @since 4.2
 */
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) {
			headers.setContentType(contentTypeToUse);
		}
	}
	if (headers.getContentLength() == -1) {
		Long contentLength = getContentLength(t, headers.getContentType());
		if (contentLength != null) {
			headers.setContentLength(contentLength);
		}
	}
}
 
Example 8
Source File: GatewayContextFilter.java    From open-cloud with MIT License 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain){
    ServerHttpRequest request = exchange.getRequest();
    GatewayContext gatewayContext = new GatewayContext();
    HttpHeaders headers = request.getHeaders();
    gatewayContext.setRequestHeaders(headers);
    gatewayContext.getAllRequestData().addAll(request.getQueryParams());
    /*
     * save gateway context into exchange
     */
    exchange.getAttributes().put(GatewayContext.CACHE_GATEWAY_CONTEXT,gatewayContext);
    MediaType contentType = headers.getContentType();
    if(headers.getContentLength()>0){
        if(MediaType.APPLICATION_JSON.equals(contentType) || MediaType.APPLICATION_JSON_UTF8.equals(contentType)){
            return readBody(exchange, chain,gatewayContext);
        }
        if(MediaType.APPLICATION_FORM_URLENCODED.equals(contentType)){
            return readFormData(exchange, chain,gatewayContext);
        }
    }
    log.debug("[GatewayContext]ContentType:{},Gateway context is set with {}",contentType, gatewayContext);
    return chain.filter(exchange);

}
 
Example 9
Source File: LoggingClientHttpRequestInterceptor.java    From GreenSummer with GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean hasTextBody(HttpHeaders headers) {
    long contentLength = headers.getContentLength();
    if (contentLength != 0) {
        MediaType contentType = headers.getContentType();
        if (contentType != null) {
            String subtype = contentType.getSubtype();
            return "text".equals(contentType.getType()) || "xml".equals(subtype) || "json".equals(subtype);
        }
    }
    return false;
}
 
Example 10
Source File: LoggingClientHttpRequestInterceptor.java    From GreenSummer with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void logBody(String body, HttpHeaders headers) {
    MediaType contentType = headers.getContentType();
    List<String> contentEncoding = headers.get(CONTENT_ENCODING_HEADER);
    if (contentEncoding != null && !contentEncoding.contains("identity")) {
        log.trace("  Body: encoded, not shown");
    } else {
        if (contentType != null && contentType.toString().startsWith(APPLICATION_JSON_HEADER)) {
            log.trace("  Body: {}", writeJSON(body));
        } else {
            log.trace("  Body: {}", body);
        }
    }
}
 
Example 11
Source File: WxMediaResourceMessageConverter.java    From FastBootWeixin with Apache License 2.0 5 votes vote down vote up
@Override
protected void addDefaultHeaders(HttpHeaders headers, Resource t, MediaType contentType) throws IOException {
    // 忽略被选择出来的类型,因为如果有选择出来的类型,会影响getDefaultContentType的获取
    super.addDefaultHeaders(headers, t, null);
    // 如果super真的拿不到contentType时,取传入的contentType
    if (headers.getContentType() == null && contentType != null) {
        headers.setContentType(contentType);
    }
}
 
Example 12
Source File: SseEmitter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void extendResponse(ServerHttpResponse outputMessage) {
	super.extendResponse(outputMessage);

	HttpHeaders headers = outputMessage.getHeaders();
	if (headers.getContentType() == null) {
		headers.setContentType(UTF8_TEXT_EVENTSTREAM);
	}
}
 
Example 13
Source File: DefaultMultipartMessageReader.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private static Charset contentTypeCharset(HttpHeaders headers) {
	MediaType contentType = headers.getContentType();
	if (contentType != null) {
		Charset charset = contentType.getCharset();
		if (charset != null) {
			return charset;
		}
	}
	return StandardCharsets.ISO_8859_1;
}
 
Example 14
Source File: DefaultResponseErrorHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Determine the charset of the response (for inclusion in a status exception).
 * @param response the response to inspect
 * @return the associated charset, or {@code null} if none
 * @since 4.3.8
 */
@Nullable
protected Charset getCharset(ClientHttpResponse response) {
	HttpHeaders headers = response.getHeaders();
	MediaType contentType = headers.getContentType();
	return (contentType != null ? contentType.getCharset() : null);
}
 
Example 15
Source File: UploadResource.java    From tutorials with MIT License 5 votes vote down vote up
/**
 *  Standard file upload.
 */
@PostMapping
public Mono<ResponseEntity<UploadResult>> uploadHandler(@RequestHeader HttpHeaders headers, @RequestBody Flux<ByteBuffer> body) {

    long length = headers.getContentLength();
    if (length < 0) {
        throw new UploadFailedException(HttpStatus.BAD_REQUEST.value(), Optional.of("required header missing: Content-Length"));
    }

    String fileKey = UUID.randomUUID().toString();
    Map<String, String> metadata = new HashMap<String, String>();
    MediaType mediaType = headers.getContentType();

    if (mediaType == null) {
        mediaType = MediaType.APPLICATION_OCTET_STREAM;
    }

    log.info("[I95] uploadHandler: mediaType{}, length={}", mediaType, length);
    CompletableFuture<PutObjectResponse> future = s3client
      .putObject(PutObjectRequest.builder()
        .bucket(s3config.getBucket())
        .contentLength(length)
        .key(fileKey.toString())
        .contentType(mediaType.toString())
        .metadata(metadata)
        .build(), 
        AsyncRequestBody.fromPublisher(body));
    
    return Mono.fromFuture(future)
      .map((response) -> {
          checkResult(response);
          return ResponseEntity
            .status(HttpStatus.CREATED)
            .body(new UploadResult(HttpStatus.CREATED, new String[] {fileKey}));
      });
}
 
Example 16
Source File: ResourceRegionHttpMessageConverter.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private void writeResourceRegionCollection(Collection<ResourceRegion> resourceRegions,
		HttpOutputMessage outputMessage) throws IOException {

	Assert.notNull(resourceRegions, "Collection of ResourceRegion should not be null");
	HttpHeaders responseHeaders = outputMessage.getHeaders();

	MediaType contentType = responseHeaders.getContentType();
	String boundaryString = MimeTypeUtils.generateMultipartBoundaryString();
	responseHeaders.set(HttpHeaders.CONTENT_TYPE, "multipart/byteranges; boundary=" + boundaryString);
	OutputStream out = outputMessage.getBody();

	for (ResourceRegion region : resourceRegions) {
		long start = region.getPosition();
		long end = start + region.getCount() - 1;
		InputStream in = region.getResource().getInputStream();
		try {
			// Writing MIME header.
			println(out);
			print(out, "--" + boundaryString);
			println(out);
			if (contentType != null) {
				print(out, "Content-Type: " + contentType.toString());
				println(out);
			}
			Long resourceLength = region.getResource().contentLength();
			end = Math.min(end, resourceLength - 1);
			print(out, "Content-Range: bytes " + start + '-' + end + '/' + resourceLength);
			println(out);
			println(out);
			// Printing content
			StreamUtils.copyRange(in, out, start, end);
		}
		finally {
			try {
				in.close();
			}
			catch (IOException ex) {
				// ignore
			}
		}
	}

	println(out);
	print(out, "--" + boundaryString + "--");
}
 
Example 17
Source File: AbstractJsonHttpMessageConverter.java    From java-technology-stack with MIT License 4 votes vote down vote up
private static Charset getCharset(HttpHeaders headers) {
	Charset charset = (headers.getContentType() != null ? headers.getContentType().getCharset() : null);
	return (charset != null ? charset : DEFAULT_CHARSET);
}
 
Example 18
Source File: MultipartHttpMessageWriter.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> Flux<DataBuffer> encodePart(byte[] boundary, String name, T value, DataBufferFactory bufferFactory) {
	MultipartHttpOutputMessage outputMessage = new MultipartHttpOutputMessage(bufferFactory, getCharset());
	HttpHeaders outputHeaders = outputMessage.getHeaders();

	T body;
	ResolvableType resolvableType = null;
	if (value instanceof HttpEntity) {
		HttpEntity<T> httpEntity = (HttpEntity<T>) value;
		outputHeaders.putAll(httpEntity.getHeaders());
		body = httpEntity.getBody();
		Assert.state(body != null, "MultipartHttpMessageWriter only supports HttpEntity with body");
		if (httpEntity instanceof ResolvableTypeProvider) {
			resolvableType = ((ResolvableTypeProvider) httpEntity).getResolvableType();
		}
	}
	else {
		body = value;
	}
	if (resolvableType == null) {
		resolvableType = ResolvableType.forClass(body.getClass());
	}

	if (!outputHeaders.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		if (body instanceof Resource) {
			outputHeaders.setContentDispositionFormData(name, ((Resource) body).getFilename());
		}
		else if (resolvableType.resolve() == Resource.class) {
			body = (T) Mono.from((Publisher<?>) body).doOnNext(o -> outputHeaders
					.setContentDispositionFormData(name, ((Resource) o).getFilename()));
		}
		else {
			outputHeaders.setContentDispositionFormData(name, null);
		}
	}

	MediaType contentType = outputHeaders.getContentType();

	final ResolvableType finalBodyType = resolvableType;
	Optional<HttpMessageWriter<?>> writer = this.partWriters.stream()
			.filter(partWriter -> partWriter.canWrite(finalBodyType, contentType))
			.findFirst();

	if (!writer.isPresent()) {
		return Flux.error(new CodecException("No suitable writer found for part: " + name));
	}

	Publisher<T> bodyPublisher =
			body instanceof Publisher ? (Publisher<T>) body : Mono.just(body);

	// The writer will call MultipartHttpOutputMessage#write which doesn't actually write
	// but only stores the body Flux and returns Mono.empty().

	Mono<Void> partContentReady = ((HttpMessageWriter<T>) writer.get())
			.write(bodyPublisher, resolvableType, contentType, outputMessage, DEFAULT_HINTS);

	// After partContentReady, we can access the part content from MultipartHttpOutputMessage
	// and use it for writing to the actual request body

	Flux<DataBuffer> partContent = partContentReady.thenMany(Flux.defer(outputMessage::getBody));

	return Flux.concat(
			generateBoundaryLine(boundary, bufferFactory),
			partContent,
			generateNewLine(bufferFactory));
}
 
Example 19
Source File: CustomResponseErrorHandler.java    From sdk-rest with MIT License 4 votes vote down vote up
private Charset getCharset(ClientHttpResponse response) {
    HttpHeaders headers = response.getHeaders();
    MediaType contentType = headers.getContentType();
    return contentType != null ? contentType.getCharSet() : null;
}
 
Example 20
Source File: MultipartHttpMessageWriter.java    From java-technology-stack with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> Flux<DataBuffer> encodePart(byte[] boundary, String name, T value) {
	MultipartHttpOutputMessage outputMessage = new MultipartHttpOutputMessage(this.bufferFactory, getCharset());
	HttpHeaders outputHeaders = outputMessage.getHeaders();

	T body;
	ResolvableType resolvableType = null;
	if (value instanceof HttpEntity) {
		HttpEntity<T> httpEntity = (HttpEntity<T>) value;
		outputHeaders.putAll(httpEntity.getHeaders());
		body = httpEntity.getBody();
		Assert.state(body != null, "MultipartHttpMessageWriter only supports HttpEntity with body");

		if (httpEntity instanceof MultipartBodyBuilder.PublisherEntity<?, ?>) {
			MultipartBodyBuilder.PublisherEntity<?, ?> publisherEntity =
					(MultipartBodyBuilder.PublisherEntity<?, ?>) httpEntity;
			resolvableType = publisherEntity.getResolvableType();
		}
	}
	else {
		body = value;
	}
	if (resolvableType == null) {
		resolvableType = ResolvableType.forClass(body.getClass());
	}

	if (!outputHeaders.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		if (body instanceof Resource) {
			outputHeaders.setContentDispositionFormData(name, ((Resource) body).getFilename());
		}
		else if (resolvableType.resolve() == Resource.class) {
			body = (T) Mono.from((Publisher<?>) body).doOnNext(o -> outputHeaders
					.setContentDispositionFormData(name, ((Resource) o).getFilename()));
		}
		else {
			outputHeaders.setContentDispositionFormData(name, null);
		}
	}

	MediaType contentType = outputHeaders.getContentType();

	final ResolvableType finalBodyType = resolvableType;
	Optional<HttpMessageWriter<?>> writer = this.partWriters.stream()
			.filter(partWriter -> partWriter.canWrite(finalBodyType, contentType))
			.findFirst();

	if (!writer.isPresent()) {
		return Flux.error(new CodecException("No suitable writer found for part: " + name));
	}

	Publisher<T> bodyPublisher =
			body instanceof Publisher ? (Publisher<T>) body : Mono.just(body);

	// The writer will call MultipartHttpOutputMessage#write which doesn't actually write
	// but only stores the body Flux and returns Mono.empty().

	Mono<Void> partContentReady = ((HttpMessageWriter<T>) writer.get())
			.write(bodyPublisher, resolvableType, contentType, outputMessage, DEFAULT_HINTS);

	// After partContentReady, we can access the part content from MultipartHttpOutputMessage
	// and use it for writing to the actual request body

	Flux<DataBuffer> partContent = partContentReady.thenMany(Flux.defer(outputMessage::getBody));

	return Flux.concat(Mono.just(generateBoundaryLine(boundary)), partContent, Mono.just(generateNewLine()));
}