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

The following examples show how to use org.springframework.http.HttpHeaders#isEmpty() . 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: 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 2
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 3
Source File: FormHttpMessageConverter.java    From lams with GNU General Public License v2.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 4
Source File: HttpHeadersReturnValueHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
@SuppressWarnings("resource")
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	mavContainer.setRequestHandled(true);

	Assert.state(returnValue instanceof HttpHeaders, "HttpHeaders expected");
	HttpHeaders headers = (HttpHeaders) returnValue;

	if (!headers.isEmpty()) {
		HttpServletResponse servletResponse = webRequest.getNativeResponse(HttpServletResponse.class);
		ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(servletResponse);
		outputMessage.getHeaders().putAll(headers);
		outputMessage.getBody();  // flush headers
	}
}
 
Example 5
Source File: AnnotationMethodHandlerAdapter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void handleHttpEntityResponse(HttpEntity<?> responseEntity, ServletWebRequest webRequest) throws Exception {
	if (responseEntity == null) {
		return;
	}
	HttpInputMessage inputMessage = createHttpInputMessage(webRequest);
	HttpOutputMessage outputMessage = createHttpOutputMessage(webRequest);
	if (responseEntity instanceof ResponseEntity && outputMessage instanceof ServerHttpResponse) {
		((ServerHttpResponse) outputMessage).setStatusCode(((ResponseEntity<?>) responseEntity).getStatusCode());
	}
	HttpHeaders entityHeaders = responseEntity.getHeaders();
	if (!entityHeaders.isEmpty()) {
		outputMessage.getHeaders().putAll(entityHeaders);
	}
	Object body = responseEntity.getBody();
	if (body != null) {
		writeWithMessageConverters(body, inputMessage, outputMessage);
	}
	else {
		// flush headers
		outputMessage.getBody();
	}
}
 
Example 6
Source File: RestTemplateHeaderInterceptor.java    From blade-tool with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public ClientHttpResponse intercept(
	HttpRequest request, byte[] bytes,
	ClientHttpRequestExecution execution) throws IOException {
	HttpHeaders headers = BladeHttpHeadersContextHolder.get();
	// 考虑2中情况 1. RestTemplate 不是用 hystrix 2. 使用 hystrix
	if (headers == null) {
		headers = BladeHttpHeadersContextHolder.toHeaders(accountGetter, properties);
	}
	if (headers != null && !headers.isEmpty()) {
		HttpHeaders httpHeaders = request.getHeaders();
		headers.forEach((key, values) -> {
			values.forEach(value -> httpHeaders.add(key, value));
		});
	}
	return execution.execute(request, bytes);
}
 
Example 7
Source File: LogFilter.java    From gateway with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 获取客户端IP
 *
 * @param headers 请求头
 * @return 客户端IP
 */
private String getIp(HttpHeaders headers) {
    if (headers.isEmpty()) {
        return null;
    }

    AtomicReference<String> ip = new AtomicReference<>(headers.getFirst("X-Real-IP"));
    if (ip.get() == null || ip.get().isEmpty()) {
        ip.set(headers.getFirst("X-Forwarded-For"));
    }

    if (ip.get() == null || ip.get().isEmpty()) {
        ip.set(headers.getFirst("Proxy-Client-IP"));
    }

    if (ip.get() == null || ip.get().isEmpty()) {
        ip.set(headers.getFirst("WL-Proxy-Client-IP"));
    }

    return ip.get();
}
 
Example 8
Source File: HttpHeadersReturnValueHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("resource")
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	mavContainer.setRequestHandled(true);

	Assert.isInstanceOf(HttpHeaders.class, returnValue);
	HttpHeaders headers = (HttpHeaders) returnValue;

	if (!headers.isEmpty()) {
		HttpServletResponse servletResponse = webRequest.getNativeResponse(HttpServletResponse.class);
		ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(servletResponse);
		outputMessage.getHeaders().putAll(headers);
		outputMessage.getBody(); // flush headers
	}
}
 
Example 9
Source File: HttpHeadersReturnValueHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("resource")
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	mavContainer.setRequestHandled(true);

	Assert.state(returnValue instanceof HttpHeaders, "HttpHeaders expected");
	HttpHeaders headers = (HttpHeaders) returnValue;

	if (!headers.isEmpty()) {
		HttpServletResponse servletResponse = webRequest.getNativeResponse(HttpServletResponse.class);
		Assert.state(servletResponse != null, "No HttpServletResponse");
		ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(servletResponse);
		outputMessage.getHeaders().putAll(headers);
		outputMessage.getBody();  // flush headers
	}
}
 
Example 10
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 11
Source File: AccessFilter.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
protected String getHeader(String headerName, ServerHttpRequest request) {
    HttpHeaders headers = request.getHeaders();
    String token = StrUtil.EMPTY;
    if (headers == null || headers.isEmpty()) {
        return token;
    }

    token = headers.getFirst(headerName);

    if (StringUtils.isNotBlank(token)) {
        return token;
    }

    return request.getQueryParams().getFirst(headerName);
}
 
Example 12
Source File: BladeHttpHeadersContextHolder.java    From blade-tool with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Nullable
public static HttpHeaders toHeaders(
	@Nullable BladeHystrixAccountGetter accountGetter,
	BladeHystrixHeadersProperties properties) {
	HttpServletRequest request = WebUtil.getRequest();
	if (request == null) {
		return null;
	}
	HttpHeaders headers = new HttpHeaders();
	String accountHeaderName = properties.getAccount();
	// 如果配置有 account 读取器
	if (accountGetter != null) {
		String xAccountHeader = accountGetter.get(request);
		if (StringUtil.isNotBlank(xAccountHeader)) {
			headers.add(accountHeaderName, xAccountHeader);
		}
	}
	List<String> allowHeadsList = new ArrayList<>(Arrays.asList(ALLOW_HEADS));
	// 如果有传递 account header 继续往下层传递
	allowHeadsList.add(accountHeaderName);
	// 传递请求头
	Enumeration<String> headerNames = request.getHeaderNames();
	if (headerNames != null) {
		List<String> allowed = properties.getAllowed();
		String pattern = properties.getPattern();
		while (headerNames.hasMoreElements()) {
			String key = headerNames.nextElement();
			// 只支持配置的 header
			if (allowHeadsList.contains(key) || allowed.contains(key) || PatternMatchUtils.simpleMatch(pattern, key)) {
				String values = request.getHeader(key);
				// header value 不为空的 传递
				if (StringUtil.isNotBlank(values)) {
					headers.add(key, values);
				}
			}

		}
	}
	return headers.isEmpty() ? null : headers;
}
 
Example 13
Source File: BladeFeignRequestHeaderInterceptor.java    From blade-tool with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void apply(RequestTemplate requestTemplate) {
	HttpHeaders headers = BladeHttpHeadersContextHolder.get();
	if (headers != null && !headers.isEmpty()) {
		headers.forEach((key, values) -> {
			values.forEach(value -> requestTemplate.header(key, value));
		});
	}
}
 
Example 14
Source File: RestTemplateEurekaHttpClient.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
private static Map<String, String> headersOf(ResponseEntity<?> response) {
	HttpHeaders httpHeaders = response.getHeaders();
	if (httpHeaders == null || httpHeaders.isEmpty()) {
		return Collections.emptyMap();
	}
	Map<String, String> headers = new HashMap<>();
	for (Entry<String, List<String>> entry : httpHeaders.entrySet()) {
		if (!entry.getValue().isEmpty()) {
			headers.put(entry.getKey(), entry.getValue().get(0));
		}
	}
	return headers;
}
 
Example 15
Source File: HttpEntityMethodProcessor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	mavContainer.setRequestHandled(true);
	if (returnValue == null) {
		return;
	}

	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);

	Assert.isInstanceOf(HttpEntity.class, returnValue);
	HttpEntity<?> responseEntity = (HttpEntity<?>) returnValue;

	HttpHeaders entityHeaders = responseEntity.getHeaders();
	if (!entityHeaders.isEmpty()) {
		outputMessage.getHeaders().putAll(entityHeaders);
	}

	Object body = responseEntity.getBody();
	if (responseEntity instanceof ResponseEntity) {
		outputMessage.setStatusCode(((ResponseEntity<?>) responseEntity).getStatusCode());
		if (HttpMethod.GET == inputMessage.getMethod() && isResourceNotModified(inputMessage, outputMessage)) {
			outputMessage.setStatusCode(HttpStatus.NOT_MODIFIED);
			// Ensure headers are flushed, no body should be written.
			outputMessage.flush();
			// Skip call to converters, as they may update the body.
			return;
		}
	}

	// Try even with null body. ResponseBodyAdvice could get involved.
	writeWithMessageConverters(body, returnType, inputMessage, outputMessage);

	// Ensure headers are flushed even if no body was written.
	outputMessage.flush();
}
 
Example 16
Source File: HttpWebHandlerAdapter.java    From java-technology-stack with MIT License 4 votes vote down vote up
private String formatHeaders(HttpHeaders responseHeaders) {
	return this.enableLoggingRequestDetails ?
			responseHeaders.toString() : responseHeaders.isEmpty() ? "{}" : "{masked}";
}
 
Example 17
Source File: ExchangeFunctions.java    From java-technology-stack with MIT License 4 votes vote down vote up
private String formatHeaders(HttpHeaders headers) {
	return this.enableLoggingRequestDetails ? headers.toString() : headers.isEmpty() ? "{}" : "{masked}";
}
 
Example 18
Source File: HttpWebHandlerAdapter.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private String formatHeaders(HttpHeaders responseHeaders) {
	return this.enableLoggingRequestDetails ?
			responseHeaders.toString() : responseHeaders.isEmpty() ? "{}" : "{masked}";
}
 
Example 19
Source File: HttpEntityMethodProcessor.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	mavContainer.setRequestHandled(true);
	if (returnValue == null) {
		return;
	}

	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);

	Assert.isInstanceOf(HttpEntity.class, returnValue);
	HttpEntity<?> responseEntity = (HttpEntity<?>) returnValue;

	HttpHeaders outputHeaders = outputMessage.getHeaders();
	HttpHeaders entityHeaders = responseEntity.getHeaders();
	if (!entityHeaders.isEmpty()) {
		entityHeaders.forEach((key, value) -> {
			if (HttpHeaders.VARY.equals(key) && outputHeaders.containsKey(HttpHeaders.VARY)) {
				List<String> values = getVaryRequestHeadersToAdd(outputHeaders, entityHeaders);
				if (!values.isEmpty()) {
					outputHeaders.setVary(values);
				}
			}
			else {
				outputHeaders.put(key, value);
			}
		});
	}

	if (responseEntity instanceof ResponseEntity) {
		int returnStatus = ((ResponseEntity<?>) responseEntity).getStatusCodeValue();
		outputMessage.getServletResponse().setStatus(returnStatus);
		if (returnStatus == 200) {
			if (SAFE_METHODS.contains(inputMessage.getMethod())
					&& isResourceNotModified(inputMessage, outputMessage)) {
				// Ensure headers are flushed, no body should be written.
				outputMessage.flush();
				ShallowEtagHeaderFilter.disableContentCaching(inputMessage.getServletRequest());
				// Skip call to converters, as they may update the body.
				return;
			}
		}
		else if (returnStatus / 100 == 3) {
			String location = outputHeaders.getFirst("location");
			if (location != null) {
				saveFlashAttributes(mavContainer, webRequest, location);
			}
		}
	}

	// Try even with null body. ResponseBodyAdvice could get involved.
	writeWithMessageConverters(responseEntity.getBody(), returnType, inputMessage, outputMessage);

	// Ensure headers are flushed even if no body was written.
	outputMessage.flush();
}
 
Example 20
Source File: HttpEntityMethodProcessor.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	mavContainer.setRequestHandled(true);
	if (returnValue == null) {
		return;
	}

	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);

	Assert.isInstanceOf(HttpEntity.class, returnValue);
	HttpEntity<?> responseEntity = (HttpEntity<?>) returnValue;

	HttpHeaders outputHeaders = outputMessage.getHeaders();
	HttpHeaders entityHeaders = responseEntity.getHeaders();
	if (!entityHeaders.isEmpty()) {
		for (Map.Entry<String, List<String>> entry : entityHeaders.entrySet()) {
			if (HttpHeaders.VARY.equals(entry.getKey()) && outputHeaders.containsKey(HttpHeaders.VARY)) {
				List<String> values = getVaryRequestHeadersToAdd(outputHeaders, entityHeaders);
				if (!values.isEmpty()) {
					outputHeaders.setVary(values);
				}
			}
			else {
				outputHeaders.put(entry.getKey(), entry.getValue());
			}
		}
	}

	if (responseEntity instanceof ResponseEntity) {
		int returnStatus = ((ResponseEntity<?>) responseEntity).getStatusCodeValue();
		outputMessage.getServletResponse().setStatus(returnStatus);
		if (returnStatus == 200) {
			if (isResourceNotModified(inputMessage, outputMessage)) {
				// Ensure headers are flushed, no body should be written.
				outputMessage.flush();
				// Skip call to converters, as they may update the body.
				return;
			}
		}
	}

	// Try even with null body. ResponseBodyAdvice could get involved.
	writeWithMessageConverters(responseEntity.getBody(), returnType, inputMessage, outputMessage);

	// Ensure headers are flushed even if no body was written.
	outputMessage.flush();
}