Example usage for org.springframework.http HttpHeaders add

List of usage examples for org.springframework.http HttpHeaders add

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders add.

Prototype

@Override
public void add(String headerName, @Nullable String headerValue) 

Source Link

Document

Add the given, single header value under the given name.

Usage

From source file:org.springframework.http.codec.multipart.DefaultMultipartMessageReader.java

/**
 * Convert the given data buffer into a {@link HttpHeaders} instance. The given string is read
 * as US-ASCII, then split along \r\n line boundaries, each line containing a header name and
 * value(s)./*  ww w. j a  va2 s  .c  o  m*/
 */
private static HttpHeaders toHeaders(DataBuffer dataBuffer) {
    byte[] bytes = new byte[dataBuffer.readableByteCount()];
    dataBuffer.read(bytes);
    DataBufferUtils.release(dataBuffer);
    String string = new String(bytes, StandardCharsets.US_ASCII);
    String[] lines = string.split(HEADER_SEPARATOR);
    HttpHeaders result = new HttpHeaders();
    for (String line : lines) {
        int idx = line.indexOf(':');
        if (idx != -1) {
            String name = line.substring(0, idx);
            String value = line.substring(idx + 1);
            while (value.startsWith(" ")) {
                value = value.substring(1);
            }
            String[] tokens = StringUtils.tokenizeToStringArray(value, ",");
            for (String token : tokens) {
                result.add(name, token);
            }
        }
    }
    return result;
}

From source file:org.springframework.http.codec.ResourceHttpMessageWriter.java

@Override
@SuppressWarnings("unchecked")
public Mono<Void> write(Publisher<? extends Resource> inputStream, @Nullable ResolvableType actualType,
        ResolvableType elementType, @Nullable MediaType mediaType, ServerHttpRequest request,
        ServerHttpResponse response, Map<String, Object> hints) {

    HttpHeaders headers = response.getHeaders();
    headers.set(HttpHeaders.ACCEPT_RANGES, "bytes");

    List<HttpRange> ranges;
    try {/*  w  ww.  jav a  2  s  .c o  m*/
        ranges = request.getHeaders().getRange();
    } catch (IllegalArgumentException ex) {
        response.setStatusCode(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE);
        return response.setComplete();
    }

    return Mono.from(inputStream).flatMap(resource -> {

        if (ranges.isEmpty()) {
            return writeResource(resource, elementType, mediaType, response, hints);
        }

        response.setStatusCode(HttpStatus.PARTIAL_CONTENT);
        List<ResourceRegion> regions = HttpRange.toResourceRegions(ranges, resource);
        MediaType resourceMediaType = getResourceMediaType(mediaType, resource, hints);

        if (regions.size() == 1) {
            ResourceRegion region = regions.get(0);
            headers.setContentType(resourceMediaType);
            long contentLength = lengthOf(resource);
            if (contentLength != -1) {
                long start = region.getPosition();
                long end = start + region.getCount() - 1;
                end = Math.min(end, contentLength - 1);
                headers.add("Content-Range", "bytes " + start + '-' + end + '/' + contentLength);
                headers.setContentLength(end - start + 1);
            }
            return writeSingleRegion(region, response, hints);
        } else {
            String boundary = MimeTypeUtils.generateMultipartBoundaryString();
            MediaType multipartType = MediaType.parseMediaType("multipart/byteranges;boundary=" + boundary);
            headers.setContentType(multipartType);
            Map<String, Object> allHints = Hints.merge(hints, ResourceRegionEncoder.BOUNDARY_STRING_HINT,
                    boundary);
            return encodeAndWriteRegions(Flux.fromIterable(regions), resourceMediaType, response, allHints);
        }
    });
}

From source file:org.springframework.http.server.reactive.ServletServerHttpRequest.java

private static HttpHeaders initHeaders(HttpServletRequest request) {
    HttpHeaders headers = new HttpHeaders();
    for (Enumeration<?> names = request.getHeaderNames(); names.hasMoreElements();) {
        String name = (String) names.nextElement();
        for (Enumeration<?> values = request.getHeaders(name); values.hasMoreElements();) {
            headers.add(name, (String) values.nextElement());
        }//from   w ww. j  a va 2s.  c  om
    }
    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;
}

From source file:org.springframework.ide.eclipse.boot.wizard.github.auth.BasicAuthCredentials.java

@Override
public RestTemplate apply(RestTemplate rest) {
    List<ClientHttpRequestInterceptor> interceptors = rest.getInterceptors();
    interceptors.add(new ClientHttpRequestInterceptor() {
        public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                ClientHttpRequestExecution execution) throws IOException {
            if (matchHost(request.getURI().getHost())) {
                HttpHeaders headers = request.getHeaders();
                if (!headers.containsKey("Authorization")) {
                    String authString = computeAuthString();
                    headers.add("Authorization", authString);
                }//w  w  w  .j  a  v  a  2s.  c  om
            }
            return execution.execute(request, body);
        }

    });
    return rest;
}

From source file:org.springframework.integration.http.support.DefaultHttpHeaderMapper.java

private void setHttpHeader(HttpHeaders target, String name, Object value) {
    if (ACCEPT.equalsIgnoreCase(name)) {
        if (value instanceof Collection<?>) {
            Collection<?> values = (Collection<?>) value;
            if (!CollectionUtils.isEmpty(values)) {
                List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
                for (Object type : values) {
                    if (type instanceof MediaType) {
                        acceptableMediaTypes.add((MediaType) type);
                    } else if (type instanceof String) {
                        acceptableMediaTypes.addAll(MediaType.parseMediaTypes((String) type));
                    } else {
                        Class<?> clazz = (type != null) ? type.getClass() : null;
                        throw new IllegalArgumentException(
                                "Expected MediaType or String value for 'Accept' header value, but received: "
                                        + clazz);
                    }/*w w  w .  j a  v a2  s  .c o m*/
                }
                target.setAccept(acceptableMediaTypes);
            }
        } else if (value instanceof MediaType) {
            target.setAccept(Collections.singletonList((MediaType) value));
        } else if (value instanceof String[]) {
            List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
            for (String next : (String[]) value) {
                acceptableMediaTypes.add(MediaType.parseMediaType(next));
            }
            target.setAccept(acceptableMediaTypes);
        } else if (value instanceof String) {
            target.setAccept(MediaType.parseMediaTypes((String) value));
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected MediaType or String value for 'Accept' header value, but received: " + clazz);
        }
    } else if (ACCEPT_CHARSET.equalsIgnoreCase(name)) {
        if (value instanceof Collection<?>) {
            Collection<?> values = (Collection<?>) value;
            if (!CollectionUtils.isEmpty(values)) {
                List<Charset> acceptableCharsets = new ArrayList<Charset>();
                for (Object charset : values) {
                    if (charset instanceof Charset) {
                        acceptableCharsets.add((Charset) charset);
                    } else if (charset instanceof String) {
                        acceptableCharsets.add(Charset.forName((String) charset));
                    } else {
                        Class<?> clazz = (charset != null) ? charset.getClass() : null;
                        throw new IllegalArgumentException(
                                "Expected Charset or String value for 'Accept-Charset' header value, but received: "
                                        + clazz);
                    }
                }
                target.setAcceptCharset(acceptableCharsets);
            }
        } else if (value instanceof Charset[] || value instanceof String[]) {
            List<Charset> acceptableCharsets = new ArrayList<Charset>();
            Object[] values = ObjectUtils.toObjectArray(value);
            for (Object charset : values) {
                if (charset instanceof Charset) {
                    acceptableCharsets.add((Charset) charset);
                } else if (charset instanceof String) {
                    acceptableCharsets.add(Charset.forName((String) charset));
                }
            }
            target.setAcceptCharset(acceptableCharsets);
        } else if (value instanceof Charset) {
            target.setAcceptCharset(Collections.singletonList((Charset) value));
        } else if (value instanceof String) {
            String[] charsets = StringUtils.commaDelimitedListToStringArray((String) value);
            List<Charset> acceptableCharsets = new ArrayList<Charset>();
            for (String charset : charsets) {
                acceptableCharsets.add(Charset.forName(charset.trim()));
            }
            target.setAcceptCharset(acceptableCharsets);
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected Charset or String value for 'Accept-Charset' header value, but received: "
                            + clazz);
        }
    } else if (ALLOW.equalsIgnoreCase(name)) {
        if (value instanceof Collection<?>) {
            Collection<?> values = (Collection<?>) value;
            if (!CollectionUtils.isEmpty(values)) {
                Set<HttpMethod> allowedMethods = new HashSet<HttpMethod>();
                for (Object method : values) {
                    if (method instanceof HttpMethod) {
                        allowedMethods.add((HttpMethod) method);
                    } else if (method instanceof String) {
                        allowedMethods.add(HttpMethod.valueOf((String) method));
                    } else {
                        Class<?> clazz = (method != null) ? method.getClass() : null;
                        throw new IllegalArgumentException(
                                "Expected HttpMethod or String value for 'Allow' header value, but received: "
                                        + clazz);
                    }
                }
                target.setAllow(allowedMethods);
            }
        } else {
            if (value instanceof HttpMethod) {
                target.setAllow(Collections.singleton((HttpMethod) value));
            } else if (value instanceof HttpMethod[]) {
                Set<HttpMethod> allowedMethods = new HashSet<HttpMethod>();
                for (HttpMethod next : (HttpMethod[]) value) {
                    allowedMethods.add(next);
                }
                target.setAllow(allowedMethods);
            } else if (value instanceof String || value instanceof String[]) {
                String[] values = (value instanceof String[]) ? (String[]) value
                        : StringUtils.commaDelimitedListToStringArray((String) value);
                Set<HttpMethod> allowedMethods = new HashSet<HttpMethod>();
                for (String next : values) {
                    allowedMethods.add(HttpMethod.valueOf(next.trim()));
                }
                target.setAllow(allowedMethods);
            } else {
                Class<?> clazz = (value != null) ? value.getClass() : null;
                throw new IllegalArgumentException(
                        "Expected HttpMethod or String value for 'Allow' header value, but received: " + clazz);
            }
        }
    } else if (CACHE_CONTROL.equalsIgnoreCase(name)) {
        if (value instanceof String) {
            target.setCacheControl((String) value);
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected String value for 'Cache-Control' header value, but received: " + clazz);
        }
    } else if (CONTENT_LENGTH.equalsIgnoreCase(name)) {
        if (value instanceof Number) {
            target.setContentLength(((Number) value).longValue());
        } else if (value instanceof String) {
            target.setContentLength(Long.parseLong((String) value));
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected Number or String value for 'Content-Length' header value, but received: "
                            + clazz);
        }
    } else if (CONTENT_TYPE.equalsIgnoreCase(name)) {
        if (value instanceof MediaType) {
            target.setContentType((MediaType) value);
        } else if (value instanceof String) {
            target.setContentType(MediaType.parseMediaType((String) value));
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected MediaType or String value for 'Content-Type' header value, but received: "
                            + clazz);
        }
    } else if (DATE.equalsIgnoreCase(name)) {
        if (value instanceof Date) {
            target.setDate(((Date) value).getTime());
        } else if (value instanceof Number) {
            target.setDate(((Number) value).longValue());
        } else if (value instanceof String) {
            target.setDate(Long.parseLong((String) value));
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected Date, Number, or String value for 'Date' header value, but received: " + clazz);
        }
    } else if (ETAG.equalsIgnoreCase(name)) {
        if (value instanceof String) {
            target.setETag((String) value);
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected String value for 'ETag' header value, but received: " + clazz);
        }
    } else if (EXPIRES.equalsIgnoreCase(name)) {
        if (value instanceof Date) {
            target.setExpires(((Date) value).getTime());
        } else if (value instanceof Number) {
            target.setExpires(((Number) value).longValue());
        } else if (value instanceof String) {
            target.setExpires(Long.parseLong((String) value));
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected Date, Number, or String value for 'Expires' header value, but received: "
                            + clazz);
        }
    } else if (IF_MODIFIED_SINCE.equalsIgnoreCase(name)) {
        if (value instanceof Date) {
            target.setIfModifiedSince(((Date) value).getTime());
        } else if (value instanceof Number) {
            target.setIfModifiedSince(((Number) value).longValue());
        } else if (value instanceof String) {
            target.setIfModifiedSince(Long.parseLong((String) value));
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected Date, Number, or String value for 'If-Modified-Since' header value, but received: "
                            + clazz);
        }
    } else if (IF_NONE_MATCH.equalsIgnoreCase(name)) {
        if (value instanceof String) {
            target.setIfNoneMatch((String) value);
        } else if (value instanceof String[]) {
            String delmitedString = StringUtils.arrayToCommaDelimitedString((String[]) value);
            target.setIfNoneMatch(delmitedString);
        } else if (value instanceof Collection) {
            Collection<?> values = (Collection<?>) value;
            if (!CollectionUtils.isEmpty(values)) {
                List<String> ifNoneMatchList = new ArrayList<String>();
                for (Object next : values) {
                    if (next instanceof String) {
                        ifNoneMatchList.add((String) next);
                    } else {
                        Class<?> clazz = (next != null) ? next.getClass() : null;
                        throw new IllegalArgumentException(
                                "Expected String value for 'If-None-Match' header value, but received: "
                                        + clazz);
                    }
                }
                target.setIfNoneMatch(ifNoneMatchList);
            }
        }
    } else if (LAST_MODIFIED.equalsIgnoreCase(name)) {
        if (value instanceof Date) {
            target.setLastModified(((Date) value).getTime());
        } else if (value instanceof Number) {
            target.setLastModified(((Number) value).longValue());
        } else if (value instanceof String) {
            target.setLastModified(Long.parseLong((String) value));
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected Date, Number, or String value for 'Last-Modified' header value, but received: "
                            + clazz);
        }
    } else if (LOCATION.equalsIgnoreCase(name)) {
        if (value instanceof URI) {
            target.setLocation((URI) value);
        } else if (value instanceof String) {
            try {
                target.setLocation(new URI((String) value));
            } catch (URISyntaxException e) {
                throw new IllegalArgumentException(e);
            }
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected URI or String value for 'Location' header value, but received: " + clazz);
        }
    } else if (PRAGMA.equalsIgnoreCase(name)) {
        if (value instanceof String) {
            target.setPragma((String) value);
        } else {
            Class<?> clazz = (value != null) ? value.getClass() : null;
            throw new IllegalArgumentException(
                    "Expected String value for 'Pragma' header value, but received: " + clazz);
        }
    } else if (value instanceof String) {
        target.set(name, (String) value);
    } else if (value instanceof String[]) {
        for (String next : (String[]) value) {
            target.add(name, next);
        }
    } else if (value instanceof Iterable<?>) {
        for (Object next : (Iterable<?>) value) {
            String convertedValue = null;
            if (next instanceof String) {
                convertedValue = (String) next;
            } else {
                convertedValue = this.convertToString(value);
            }
            if (StringUtils.hasText(convertedValue)) {
                target.add(name, (String) next);
            } else {
                logger.warn("Element of the header '" + name + "' with value '" + value
                        + "' will not be set since it is not a String and no Converter "
                        + "is available. Consider registering a Converter with ConversionService (e.g., <int:converter>)");
            }
        }
    } else {
        String convertedValue = this.convertToString(value);
        if (StringUtils.hasText(convertedValue)) {
            target.set(name, convertedValue);
        } else {
            logger.warn("Header '" + name + "' with value '" + value
                    + "' will not be set since it is not a String and no Converter "
                    + "is available. Consider registering a Converter with ConversionService (e.g., <int:converter>)");
        }
    }
}

From source file:org.springframework.integration.samples.rest.RestHttpClientTest.java

/**
 *
 * @throws Exception//from  ww w.  j a v  a  2s. c  o  m
 */
@Test
public void testGetEmployeeAsXml() throws Exception {

    Map<String, Object> employeeSearchMap = getEmployeeSearchMap("0");

    final String fullUrl = "http://localhost:8080/rest-http/services/employee/{id}/search";

    EmployeeList employeeList = restTemplate.execute(fullUrl, HttpMethod.GET, new RequestCallback() {
        @Override
        public void doWithRequest(ClientHttpRequest request) throws IOException {
            HttpHeaders headers = getHttpHeadersWithUserCredentials(request);
            headers.add("Accept", "application/xml");
        }
    }, responseExtractor, employeeSearchMap);

    logger.info("The employee list size :" + employeeList.getEmployee().size());

    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);

    marshaller.marshal(employeeList, sr);
    logger.info(sr.getWriter().toString());
    assertTrue(employeeList.getEmployee().size() > 0);
}

From source file:org.springframework.integration.samples.rest.RestHttpClientTest.java

@Test
public void testGetEmployeeAsJson() throws Exception {
    Map<String, Object> employeeSearchMap = getEmployeeSearchMap("0");

    final String fullUrl = "http://localhost:8080/rest-http/services/employee/{id}/search?format=json";
    HttpHeaders headers = getHttpHeadersWithUserCredentials(new HttpHeaders());
    headers.add("Accept", "application/json");
    HttpEntity<Object> request = new HttpEntity<Object>(headers);

    ResponseEntity<?> httpResponse = restTemplate.exchange(fullUrl, HttpMethod.GET, request, EmployeeList.class,
            employeeSearchMap);/*  w w w  . j av a2  s . c o  m*/
    logger.info("Return Status :" + httpResponse.getHeaders().get("X-Return-Status"));
    logger.info("Return Status Message :" + httpResponse.getHeaders().get("X-Return-Status-Msg"));
    assertTrue(httpResponse.getStatusCode().equals(HttpStatus.OK));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    jaxbJacksonObjectMapper.writeValue(out, httpResponse.getBody());
    logger.info(new String(out.toByteArray()));
}

From source file:org.springframework.integration.samples.rest.RestHttpClientTest.java

private HttpHeaders getHttpHeadersWithUserCredentials(HttpHeaders headers) {

    String username = "SPRING";
    String password = "spring";

    String combinedUsernamePassword = username + ":" + password;
    byte[] base64Token = Base64.getEncoder().encode(combinedUsernamePassword.getBytes());
    String base64EncodedToken = new String(base64Token);
    //adding Authorization header for HTTP Basic authentication
    headers.add("Authorization", "Basic  " + base64EncodedToken);

    return headers;
}

From source file:org.springframework.samples.portfolio.web.tomcat.IntegrationPortfolioTests.java

private static void loginAndSaveJsessionIdCookie(final String user, final String password,
        final HttpHeaders headersToUpdate) {

    String url = "http://localhost:" + port + "/login.html";

    new RestTemplate().execute(url, HttpMethod.POST,

            new RequestCallback() {
                @Override// w  ww . java 2  s  . com
                public void doWithRequest(ClientHttpRequest request) throws IOException {
                    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
                    map.add("username", user);
                    map.add("password", password);
                    new FormHttpMessageConverter().write(map, MediaType.APPLICATION_FORM_URLENCODED, request);
                }
            },

            new ResponseExtractor<Object>() {
                @Override
                public Object extractData(ClientHttpResponse response) throws IOException {
                    headersToUpdate.add("Cookie", response.getHeaders().getFirst("Set-Cookie"));
                    return null;
                }
            });
}

From source file:org.springframework.web.reactive.socket.WebSocketIntegrationTests.java

@Test
public void customHeader() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.add("my-header", "my-value");
    MonoProcessor<Object> output = MonoProcessor.create();

    this.client.execute(getUrl("/custom-header"), headers,
            session -> session.receive().map(WebSocketMessage::getPayloadAsText).subscribeWith(output).then())
            .block(Duration.ofMillis(5000));

    assertEquals("my-header:my-value", output.block(Duration.ofMillis(5000)));
}