下面列出了org.springframework.http.HttpHeaders#getContentLength ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException {
if (this.body == null) {
if (this.outputStreaming) {
long contentLength = headers.getContentLength();
if (contentLength >= 0) {
this.connection.setFixedLengthStreamingMode(contentLength);
}
else {
this.connection.setChunkedStreamingMode(this.chunkSize);
}
}
SimpleBufferingClientHttpRequest.addHeaders(this.connection, headers);
this.connection.connect();
this.body = this.connection.getOutputStream();
}
return StreamUtils.nonClosing(this.body);
}
private Mono<Void> writeResource(Resource resource, ResolvableType type, @Nullable MediaType mediaType,
ReactiveHttpOutputMessage message, Map<String, Object> hints) {
HttpHeaders headers = message.getHeaders();
MediaType resourceMediaType = getResourceMediaType(mediaType, resource, hints);
headers.setContentType(resourceMediaType);
if (headers.getContentLength() < 0) {
long length = lengthOf(resource);
if (length != -1) {
headers.setContentLength(length);
}
}
return zeroCopy(resource, null, message, hints)
.orElseGet(() -> {
Mono<Resource> input = Mono.just(resource);
DataBufferFactory factory = message.bufferFactory();
Flux<DataBuffer> body = this.encoder.encode(input, factory, type, resourceMediaType, hints);
return message.writeWith(body);
});
}
@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);
}
@Override
protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException {
if (this.body == null) {
if (this.outputStreaming) {
int contentLength = (int) headers.getContentLength();
if (contentLength >= 0) {
this.connection.setFixedLengthStreamingMode(contentLength);
}
else {
this.connection.setChunkedStreamingMode(this.chunkSize);
}
}
SimpleBufferingClientHttpRequest.addHeaders(this.connection, headers);
this.connection.connect();
this.body = this.connection.getOutputStream();
}
return StreamUtils.nonClosing(this.body);
}
@Override
protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException {
if (this.body == null) {
if (this.outputStreaming) {
int contentLength = (int) headers.getContentLength();
if (contentLength >= 0) {
this.connection.setFixedLengthStreamingMode(contentLength);
}
else {
this.connection.setChunkedStreamingMode(this.chunkSize);
}
}
SimpleBufferingClientHttpRequest.addHeaders(this.connection, headers);
this.connection.connect();
this.body = this.connection.getOutputStream();
}
return StreamUtils.nonClosing(this.body);
}
protected void exceptionIfImageSizeGreaterThanAvailableCapacity(String url) {
if (CoreGlobalProperty.UNIT_TEST_ON) {
return;
}
url = url.trim();
if (!url.startsWith("http") && !url.startsWith("https")) {
return;
}
HttpHeaders header;
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setReadTimeout(CoreGlobalProperty.REST_FACADE_READ_TIMEOUT);
factory.setConnectTimeout(CoreGlobalProperty.REST_FACADE_CONNECT_TIMEOUT);
factory.setHttpClient(HttpClients.createDefault());
RestTemplate template = new RestTemplate(factory);
try {
header = template.headForHeaders(URI.create(url));
logger.debug(String.format("get header from %s: %s", url, header));
} catch (Exception e) {
throw new OperationFailureException(operr("failed to get header of image url %s: %s", url, e.toString()));
}
if (header == null) {
throw new OperationFailureException(operr("failed to get header of image url %s", url));
}
long size = header.getContentLength();
if (size == -1) {
logger.error(String.format("failed to get image size from url %s, but ignore this error and proceed", url));
} else if (size < ImageConstant.MINI_IMAGE_SIZE_IN_BYTE) {
throw new OperationFailureException(operr("the image size get from url %s is %d bytes, " +
"it's too small for an image, please check the url again.", url, size));
} else if (size > self.getAvailableCapacity()) {
throw new OperationFailureException(operr("the backup storage[uuid:%s, name:%s] has not enough capacity to download the image[%s]." +
"Required size:%s, available size:%s", self.getUuid(), self.getName(), url, size, self.getAvailableCapacity()));
}
}
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers) throws IOException {
byte[] bytes = this.bufferedOutput.toByteArray();
if (headers.getContentLength() < 0) {
headers.setContentLength(bytes.length);
}
ListenableFuture<ClientHttpResponse> result = executeInternal(headers, bytes);
this.bufferedOutput = null;
return result;
}
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
byte[] bytes = this.bufferedOutput.toByteArray();
if (headers.getContentLength() < 0) {
headers.setContentLength(bytes.length);
}
ClientHttpResponse result = executeInternal(headers, bytes);
this.bufferedOutput = new ByteArrayOutputStream(0);
return result;
}
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers) throws IOException {
byte[] bytes = this.bufferedOutput.toByteArray();
if (headers.getContentLength() < 0) {
headers.setContentLength(bytes.length);
}
ListenableFuture<ClientHttpResponse> result = executeInternal(headers, bytes);
this.bufferedOutput = new ByteArrayOutputStream(0);
return result;
}
private static HttpHeaders initHeaders(HttpHeaders headers, HttpServletRequest request) {
MediaType contentType = headers.getContentType();
if (contentType == null) {
String requestContentType = request.getContentType();
if (StringUtils.hasLength(requestContentType)) {
contentType = MediaType.parseMediaType(requestContentType);
headers.setContentType(contentType);
}
}
if (contentType != null && contentType.getCharset() == null) {
String encoding = request.getCharacterEncoding();
if (StringUtils.hasLength(encoding)) {
Charset charset = Charset.forName(encoding);
Map<String, String> params = new LinkedCaseInsensitiveMap<>();
params.putAll(contentType.getParameters());
params.put("charset", charset.toString());
headers.setContentType(
new MediaType(contentType.getType(), contentType.getSubtype(),
params));
}
}
if (headers.getContentLength() == -1) {
int contentLength = request.getContentLength();
if (contentLength != -1) {
headers.setContentLength(contentLength);
}
}
return headers;
}
@Test
public void givenResumableUrl_whenDownloadCompletely_thenExpectCorrectFileSize() {
HttpHeaders headers = restTemplate.headForHeaders(FILE_URL);
long contentLength = headers.getContentLength();
File file = restTemplate.execute(FILE_URL, HttpMethod.GET, null, clientHttpResponse -> {
File ret = File.createTempFile("download", "tmp");
StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret));
return ret;
});
Assert.assertNotNull(file);
Assertions
.assertThat(file.length())
.isEqualTo(contentLength);
}
/**
* 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}));
});
}
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers) throws IOException {
byte[] bytes = this.bufferedOutput.toByteArray();
if (headers.getContentLength() < 0) {
headers.setContentLength(bytes.length);
}
ListenableFuture<ClientHttpResponse> result = executeInternal(headers, bytes);
this.bufferedOutput = new ByteArrayOutputStream(0);
return result;
}
private static HttpHeaders initHeaders(HttpHeaders headers, HttpServletRequest request) {
MediaType contentType = headers.getContentType();
if (contentType == null) {
String requestContentType = request.getContentType();
if (StringUtils.hasLength(requestContentType)) {
contentType = MediaType.parseMediaType(requestContentType);
headers.setContentType(contentType);
}
}
if (contentType != null && contentType.getCharset() == null) {
String encoding = request.getCharacterEncoding();
if (StringUtils.hasLength(encoding)) {
Charset charset = Charset.forName(encoding);
Map<String, String> params = new LinkedCaseInsensitiveMap<>();
params.putAll(contentType.getParameters());
params.put("charset", charset.toString());
headers.setContentType(
new MediaType(contentType.getType(), contentType.getSubtype(),
params));
}
}
if (headers.getContentLength() == -1) {
int contentLength = request.getContentLength();
if (contentLength != -1) {
headers.setContentLength(contentLength);
}
}
return headers;
}
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
byte[] bytes = this.bufferedOutput.toByteArray();
if (headers.getContentLength() == -1) {
headers.setContentLength(bytes.length);
}
ClientHttpResponse result = executeInternal(headers, bytes);
this.bufferedOutput = null;
return result;
}
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;
}
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers) throws IOException {
byte[] bytes = this.bufferedOutput.toByteArray();
if (headers.getContentLength() == -1) {
headers.setContentLength(bytes.length);
}
ListenableFuture<ClientHttpResponse> result = executeInternal(headers, bytes);
this.bufferedOutput = null;
return result;
}
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
byte[] bytes = this.bufferedOutput.toByteArray();
if (headers.getContentLength() < 0) {
headers.setContentLength(bytes.length);
}
ClientHttpResponse result = executeInternal(headers, bytes);
this.bufferedOutput = null;
return result;
}
private int getContentLength(HttpHeaders headers) {
// Until this is fixed https://github.com/synchronoss/nio-multipart/issues/10
long length = headers.getContentLength();
return (int) length == length ? (int) length : -1;
}
private int getContentLength(HttpHeaders headers) {
// Until this is fixed https://github.com/synchronoss/nio-multipart/issues/10
long length = headers.getContentLength();
return (int) length == length ? (int) length : -1;
}