HttpHeaders.java 46.7 KB
Newer Older
1
/*
2
 * Copyright 2002-2017 the original author or authors.
3 4 5 6 7
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9 10 11 12 13 14 15 16
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

17
package org.springframework.http;
18

19
import java.io.Serializable;
20
import java.net.InetSocketAddress;
21
import java.net.URI;
22
import java.nio.charset.Charset;
23 24
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
A
Arjen Poutsma 已提交
25 26
import java.text.ParseException;
import java.text.SimpleDateFormat;
27 28 29
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
A
Arjen Poutsma 已提交
30
import java.util.Date;
31
import java.util.EnumSet;
32
import java.util.Iterator;
33
import java.util.LinkedHashMap;
34 35
import java.util.LinkedList;
import java.util.List;
36
import java.util.Locale;
37 38
import java.util.Map;
import java.util.Set;
A
Arjen Poutsma 已提交
39
import java.util.TimeZone;
40 41
import java.util.regex.Matcher;
import java.util.regex.Pattern;
42
import java.util.stream.Collectors;
43 44

import org.springframework.util.Assert;
45
import org.springframework.util.LinkedCaseInsensitiveMap;
A
Arjen Poutsma 已提交
46
import org.springframework.util.MultiValueMap;
47 48 49
import org.springframework.util.StringUtils;

/**
S
Sam Brannen 已提交
50
 * Represents HTTP request and response headers, mapping string header names to a list of string values.
51
 *
J
Juergen Hoeller 已提交
52 53
 * <p>In addition to the normal methods defined by {@link Map}, this class offers the following
 * convenience methods:
54 55 56 57 58
 * <ul>
 * <li>{@link #getFirst(String)} returns the first value associated with a given header name</li>
 * <li>{@link #add(String, String)} adds a header value to the list of values for a header name</li>
 * <li>{@link #set(String, String)} sets the header value to a single string value</li>
 * </ul>
59
 *
S
Sam Brannen 已提交
60
 * <p>Inspired by {@code com.sun.net.httpserver.Headers}.
61 62
 *
 * @author Arjen Poutsma
63
 * @author Sebastien Deleuze
64
 * @author Brian Clozel
65
 * @author Juergen Hoeller
66
 * @author Josh Long
67 68
 * @since 3.0
 */
69 70 71
public class HttpHeaders implements MultiValueMap<String, String>, Serializable {

	private static final long serialVersionUID = -8578554704772377436L;
72

73 74 75 76
	/**
	 * The HTTP {@code Accept} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-5.3.2">Section 5.3.2 of RFC 7231</a>
	 */
77
	public static final String ACCEPT = "Accept";
78 79 80 81
	/**
	 * The HTTP {@code Accept-Charset} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-5.3.3">Section 5.3.3 of RFC 7231</a>
	 */
82
	public static final String ACCEPT_CHARSET = "Accept-Charset";
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
	/**
	 * The HTTP {@code Accept-Encoding} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-5.3.4">Section 5.3.4 of RFC 7231</a>
	 */
	public static final String ACCEPT_ENCODING = "Accept-Encoding";
	/**
	 * The HTTP {@code Accept-Language} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-5.3.5">Section 5.3.5 of RFC 7231</a>
	 */
	public static final String ACCEPT_LANGUAGE = "Accept-Language";
	/**
	 * The HTTP {@code Accept-Ranges} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7233#section-2.3">Section 5.3.5 of RFC 7233</a>
	 */
	public static final String ACCEPT_RANGES = "Accept-Ranges";
98 99
	/**
	 * The CORS {@code Access-Control-Allow-Credentials} response header field name.
100
	 * @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommendation</a>
101 102 103 104
	 */
	public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
	/**
	 * The CORS {@code Access-Control-Allow-Headers} response header field name.
105
	 * @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommendation</a>
106 107 108 109
	 */
	public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
	/**
	 * The CORS {@code Access-Control-Allow-Methods} response header field name.
110
	 * @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommendation</a>
111 112 113 114
	 */
	public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
	/**
	 * The CORS {@code Access-Control-Allow-Origin} response header field name.
115
	 * @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommendation</a>
116 117 118 119
	 */
	public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
	/**
	 * The CORS {@code Access-Control-Expose-Headers} response header field name.
120
	 * @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommendation</a>
121 122 123 124
	 */
	public static final String ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers";
	/**
	 * The CORS {@code Access-Control-Max-Age} response header field name.
125
	 * @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommendation</a>
126 127 128 129
	 */
	public static final String ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age";
	/**
	 * The CORS {@code Access-Control-Request-Headers} request header field name.
130
	 * @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommendation</a>
131 132 133 134
	 */
	public static final String ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers";
	/**
	 * The CORS {@code Access-Control-Request-Method} request header field name.
135
	 * @see <a href="http://www.w3.org/TR/cors/">CORS W3C recommendation</a>
136 137
	 */
	public static final String ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method";
138 139 140 141 142 143 144 145 146
	/**
	 * The HTTP {@code Age} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7234#section-5.1">Section 5.1 of RFC 7234</a>
	 */
	public static final String AGE = "Age";
	/**
	 * The HTTP {@code Allow} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-7.4.1">Section 7.4.1 of RFC 7231</a>
	 */
147
	public static final String ALLOW = "Allow";
148 149 150 151 152 153 154 155 156
	/**
	 * The HTTP {@code Authorization} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7235#section-4.2">Section 4.2 of RFC 7235</a>
	 */
	public static final String AUTHORIZATION = "Authorization";
	/**
	 * The HTTP {@code Cache-Control} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7234#section-5.2">Section 5.2 of RFC 7234</a>
	 */
157
	public static final String CACHE_CONTROL = "Cache-Control";
158 159 160 161
	/**
	 * The HTTP {@code Connection} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7230#section-6.1">Section 6.1 of RFC 7230</a>
	 */
162
	public static final String CONNECTION = "Connection";
163 164 165 166 167 168 169 170 171
	/**
	 * The HTTP {@code Content-Encoding} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-3.1.2.2">Section 3.1.2.2 of RFC 7231</a>
	 */
	public static final String CONTENT_ENCODING = "Content-Encoding";
	/**
	 * The HTTP {@code Content-Disposition} header field name
	 * @see <a href="http://tools.ietf.org/html/rfc6266">RFC 6266</a>
	 */
172
	public static final String CONTENT_DISPOSITION = "Content-Disposition";
173 174 175 176 177 178 179 180 181
	/**
	 * The HTTP {@code Content-Language} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-3.1.3.2">Section 3.1.3.2 of RFC 7231</a>
	 */
	public static final String CONTENT_LANGUAGE = "Content-Language";
	/**
	 * The HTTP {@code Content-Length} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7230#section-3.3.2">Section 3.3.2 of RFC 7230</a>
	 */
182
	public static final String CONTENT_LENGTH = "Content-Length";
183 184 185 186 187 188 189 190 191 192 193 194 195 196
	/**
	 * The HTTP {@code Content-Location} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-3.1.4.2">Section 3.1.4.2 of RFC 7231</a>
	 */
	public static final String CONTENT_LOCATION = "Content-Location";
	/**
	 * The HTTP {@code Content-Range} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7233#section-4.2">Section 4.2 of RFC 7233</a>
	 */
	public static final String CONTENT_RANGE = "Content-Range";
	/**
	 * The HTTP {@code Content-Type} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-3.1.1.5">Section 3.1.1.5 of RFC 7231</a>
	 */
197
	public static final String CONTENT_TYPE = "Content-Type";
198 199 200 201 202 203 204 205 206
	/**
	 * The HTTP {@code Cookie} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc2109#section-4.3.4">Section 4.3.4 of RFC 2109</a>
	 */
	public static final String COOKIE = "Cookie";
	/**
	 * The HTTP {@code Date} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-7.1.1.2">Section 7.1.1.2 of RFC 7231</a>
	 */
207
	public static final String DATE = "Date";
208 209 210 211
	/**
	 * The HTTP {@code ETag} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7232#section-2.3">Section 2.3 of RFC 7232</a>
	 */
212
	public static final String ETAG = "ETag";
213 214 215 216 217 218 219 220 221
	/**
	 * The HTTP {@code Expect} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-5.1.1">Section 5.1.1 of RFC 7231</a>
	 */
	public static final String EXPECT = "Expect";
	/**
	 * The HTTP {@code Expires} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7234#section-5.3">Section 5.3 of RFC 7234</a>
	 */
222
	public static final String EXPIRES = "Expires";
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
	/**
	 * The HTTP {@code From} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-5.5.1">Section 5.5.1 of RFC 7231</a>
	 */
	public static final String FROM = "From";
	/**
	 * The HTTP {@code Host} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7230#section-5.4">Section 5.4 of RFC 7230</a>
	 */
	public static final String HOST = "Host";
	/**
	 * The HTTP {@code If-Match} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7232#section-3.1">Section 3.1 of RFC 7232</a>
	 */
	public static final String IF_MATCH = "If-Match";
	/**
	 * The HTTP {@code If-Modified-Since} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7232#section-3.3">Section 3.3 of RFC 7232</a>
	 */
242
	public static final String IF_MODIFIED_SINCE = "If-Modified-Since";
243 244 245 246
	/**
	 * The HTTP {@code If-None-Match} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7232#section-3.2">Section 3.2 of RFC 7232</a>
	 */
247
	public static final String IF_NONE_MATCH = "If-None-Match";
248 249 250 251 252 253 254 255 256 257 258 259 260 261
	/**
	 * The HTTP {@code If-Range} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7233#section-3.2">Section 3.2 of RFC 7233</a>
	 */
	public static final String IF_RANGE = "If-Range";
	/**
	 * The HTTP {@code If-Unmodified-Since} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7232#section-3.4">Section 3.4 of RFC 7232</a>
	 */
	public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since";
	/**
	 * The HTTP {@code Last-Modified} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7232#section-2.2">Section 2.2 of RFC 7232</a>
	 */
262
	public static final String LAST_MODIFIED = "Last-Modified";
263 264 265 266 267 268 269 270 271
	/**
	 * The HTTP {@code Link} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc5988">RFC 5988</a>
	 */
	public static final String LINK = "Link";
	/**
	 * The HTTP {@code Location} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-7.1.2">Section 7.1.2 of RFC 7231</a>
	 */
272
	public static final String LOCATION = "Location";
273 274 275 276 277 278 279 280 281
	/**
	 * The HTTP {@code Max-Forwards} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-5.1.2">Section 5.1.2 of RFC 7231</a>
	 */
	public static final String MAX_FORWARDS = "Max-Forwards";
	/**
	 * The HTTP {@code Origin} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc6454">RFC 6454</a>
	 */
282
	public static final String ORIGIN = "Origin";
283 284 285 286
	/**
	 * The HTTP {@code Pragma} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7234#section-5.4">Section 5.4 of RFC 7234</a>
	 */
287
	public static final String PRAGMA = "Pragma";
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
	/**
	 * The HTTP {@code Proxy-Authenticate} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7235#section-4.3">Section 4.3 of RFC 7235</a>
	 */
	public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate";
	/**
	 * The HTTP {@code Proxy-Authorization} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7235#section-4.4">Section 4.4 of RFC 7235</a>
	 */
	public static final String PROXY_AUTHORIZATION = "Proxy-Authorization";
	/**
	 * The HTTP {@code Range} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7233#section-3.1">Section 3.1 of RFC 7233</a>
	 */
	public static final String RANGE = "Range";
	/**
	 * The HTTP {@code Referer} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-5.5.2">Section 5.5.2 of RFC 7231</a>
	 */
	public static final String REFERER = "Referer";
	/**
	 * The HTTP {@code Retry-After} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-7.1.3">Section 7.1.3 of RFC 7231</a>
	 */
	public static final String RETRY_AFTER = "Retry-After";
	/**
	 * The HTTP {@code Server} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-7.4.2">Section 7.4.2 of RFC 7231</a>
	 */
	public static final String SERVER = "Server";
	/**
	 * The HTTP {@code Set-Cookie} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc2109#section-4.2.2">Section 4.2.2 of RFC 2109</a>
	 */
	public static final String SET_COOKIE = "Set-Cookie";
	/**
	 * The HTTP {@code Set-Cookie2} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc2965">RFC 2965</a>
	 */
	public static final String SET_COOKIE2 = "Set-Cookie2";
	/**
	 * The HTTP {@code TE} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7230#section-4.3">Section 4.3 of RFC 7230</a>
	 */
	public static final String TE = "TE";
	/**
	 * The HTTP {@code Trailer} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7230#section-4.4">Section 4.4 of RFC 7230</a>
	 */
	public static final String TRAILER = "Trailer";
	/**
	 * The HTTP {@code Transfer-Encoding} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7230#section-3.3.1">Section 3.3.1 of RFC 7230</a>
	 */
	public static final String TRANSFER_ENCODING = "Transfer-Encoding";
	/**
	 * The HTTP {@code Upgrade} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7230#section-6.7">Section 6.7 of RFC 7230</a>
	 */
347
	public static final String UPGRADE = "Upgrade";
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
	/**
	 * The HTTP {@code User-Agent} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-5.5.3">Section 5.5.3 of RFC 7231</a>
	 */
	public static final String USER_AGENT = "User-Agent";
	/**
	 * The HTTP {@code Vary} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7231#section-7.1.4">Section 7.1.4 of RFC 7231</a>
	 */
	public static final String VARY = "Vary";
	/**
	 * The HTTP {@code Via} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7230#section-5.7.1">Section 5.7.1 of RFC 7230</a>
	 */
	public static final String VIA = "Via";
	/**
	 * The HTTP {@code Warning} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7234#section-5.5">Section 5.5 of RFC 7234</a>
	 */
	public static final String WARNING = "Warning";
	/**
	 * The HTTP {@code WWW-Authenticate} header field name.
	 * @see <a href="http://tools.ietf.org/html/rfc7235#section-4.1">Section 4.1 of RFC 7235</a>
	 */
	public static final String WWW_AUTHENTICATE = "WWW-Authenticate";
A
Arjen Poutsma 已提交
373

374 375 376 377
	/**
	 * Date formats as specified in the HTTP RFC
	 * @see <a href="https://tools.ietf.org/html/rfc7231#section-7.1.1.1">Section 7.1.1.1 of RFC 7231</a>
	 */
A
Arjen Poutsma 已提交
378
	private static final String[] DATE_FORMATS = new String[] {
379 380 381
			"EEE, dd MMM yyyy HH:mm:ss zzz",
			"EEE, dd-MMM-yy HH:mm:ss zzz",
			"EEE MMM dd HH:mm:ss yyyy"
A
Arjen Poutsma 已提交
382 383
	};

384 385 386 387 388 389
	/**
	 * Pattern matching ETag multiple field values in headers such as "If-Match", "If-None-Match"
	 * @see <a href="https://tools.ietf.org/html/rfc7232#section-2.3">Section 2.3 of RFC 7232</a>
	 */
	private static final Pattern ETAG_HEADER_VALUE_PATTERN = Pattern.compile("\\*|\\s*((W\\/)?(\"[^\"]*\"))\\s*,?");

390 391
	private static final DecimalFormatSymbols DECIMAL_FORMAT_SYMBOLS = new DecimalFormatSymbols(Locale.ENGLISH);

A
Arjen Poutsma 已提交
392
	private static TimeZone GMT = TimeZone.getTimeZone("GMT");
393

J
Juergen Hoeller 已提交
394

395 396
	private final Map<String, List<String>> headers;

397

J
Juergen Hoeller 已提交
398 399 400 401
	/**
	 * Constructs a new, empty instance of the {@code HttpHeaders} object.
	 */
	public HttpHeaders() {
402
		this(new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH), false);
J
Juergen Hoeller 已提交
403 404
	}

405 406 407 408 409 410 411
	/**
	 * Private constructor that can create read-only {@code HttpHeader} instances.
	 */
	private HttpHeaders(Map<String, List<String>> headers, boolean readOnly) {
		Assert.notNull(headers, "'headers' must not be null");
		if (readOnly) {
			Map<String, List<String>> map =
412
					new LinkedCaseInsensitiveMap<>(headers.size(), Locale.ENGLISH);
413 414 415 416 417 418 419 420 421 422
			for (Entry<String, List<String>> entry : headers.entrySet()) {
				List<String> values = Collections.unmodifiableList(entry.getValue());
				map.put(entry.getKey(), values);
			}
			this.headers = Collections.unmodifiableMap(map);
		}
		else {
			this.headers = headers;
		}
	}
423 424 425


	/**
J
Juergen Hoeller 已提交
426 427
	 * Set the list of acceptable {@linkplain MediaType media types},
	 * as specified by the {@code Accept} header.
428 429 430 431
	 */
	public void setAccept(List<MediaType> acceptableMediaTypes) {
		set(ACCEPT, MediaType.toString(acceptableMediaTypes));
	}
432 433

	/**
J
Juergen Hoeller 已提交
434 435
	 * Return the list of acceptable {@linkplain MediaType media types},
	 * as specified by the {@code Accept} header.
436
	 * <p>Returns an empty list when the acceptable media types are unspecified.
437 438
	 */
	public List<MediaType> getAccept() {
439
		return MediaType.parseMediaTypes(get(ACCEPT));
440 441
	}

442
	/**
443 444
	 * Set the acceptable language ranges, as specified by the
	 * {@literal Accept-Language} header.
R
Rossen Stoyanchev 已提交
445
	 * @since 5.0
446 447 448
	 */
	public void setAcceptLanguage(List<Locale.LanguageRange> languages) {
		Assert.notNull(languages, "'languages' must not be null");
R
Rossen Stoyanchev 已提交
449 450 451 452 453 454
		DecimalFormat decimal = new DecimalFormat("0.0", DECIMAL_FORMAT_SYMBOLS);
		List<String> values = languages.stream()
				.map(range ->
						range.getWeight() == Locale.LanguageRange.MAX_WEIGHT ?
								range.getRange() :
								range.getRange() + ";q=" + decimal.format(range.getWeight()))
455 456 457 458 459
				.collect(Collectors.toList());
		set(ACCEPT_LANGUAGE, toCommaDelimitedString(values));
	}

	/**
460 461 462 463 464 465
	 * Return the acceptable language ranges from the
	 * {@literal Accept-Language} header
	 * <p>If you only need the most preferred locale use
	 * {@link #getAcceptLanguageAsLocale()} or if you need to filter based on
	 * a list of supporeted locales you can pass the returned list to
	 * {@link Locale#filter(List, Collection)}.
R
Rossen Stoyanchev 已提交
466
	 * @since 5.0
467 468 469 470 471 472 473 474 475
	 */
	public List<Locale.LanguageRange> getAcceptLanguage() {
		String value = getFirst(ACCEPT_LANGUAGE);
		if (value != null) {
			return Locale.LanguageRange.parse(value);
		}
		return Collections.emptyList();
	}

476 477 478 479 480 481 482 483 484
	/**
	 * A variant of {@link #setAcceptLanguage(List)} that sets the {@literal Accept-Language}
	 * header value to the specified locale.
	 * @since 5.0
	 */
	public void setAcceptLanguageAsLocale(Locale locale) {
		setAcceptLanguage(Collections.singletonList(new Locale.LanguageRange(locale.toLanguageTag())));
	}

R
Rossen Stoyanchev 已提交
485 486
	/**
	 * A variant of {@link #getAcceptLanguage()} that converts each
487 488
	 * {@link java.util.Locale.LanguageRange} to a {@link Locale} and returns
	 * the first one on the list.
R
Rossen Stoyanchev 已提交
489 490
	 * @since 5.0
	 */
491
	public Locale getAcceptLanguageAsLocale() {
R
Rossen Stoyanchev 已提交
492 493
		List<Locale.LanguageRange> ranges = getAcceptLanguage();
		if (ranges.isEmpty()) {
494
			return null;
R
Rossen Stoyanchev 已提交
495 496 497 498
		}
		return ranges.stream()
				.map(range -> Locale.forLanguageTag(range.getRange()))
				.filter(locale -> StringUtils.hasText(locale.getDisplayName()))
499 500
				.findFirst()
				.orElse(null);
R
Rossen Stoyanchev 已提交
501 502
	}

503 504 505 506 507 508 509 510
	/**
	 * Set the (new) value of the {@code Access-Control-Allow-Credentials} response header.
	 */
	public void setAccessControlAllowCredentials(boolean allowCredentials) {
		set(ACCESS_CONTROL_ALLOW_CREDENTIALS, Boolean.toString(allowCredentials));
	}

	/**
511
	 * Return the value of the {@code Access-Control-Allow-Credentials} response header.
512 513
	 */
	public boolean getAccessControlAllowCredentials() {
514
		return Boolean.parseBoolean(getFirst(ACCESS_CONTROL_ALLOW_CREDENTIALS));
515 516 517 518 519 520 521 522 523 524
	}

	/**
	 * Set the (new) value of the {@code Access-Control-Allow-Headers} response header.
	 */
	public void setAccessControlAllowHeaders(List<String> allowedHeaders) {
		set(ACCESS_CONTROL_ALLOW_HEADERS, toCommaDelimitedString(allowedHeaders));
	}

	/**
525
	 * Return the value of the {@code Access-Control-Allow-Headers} response header.
526 527
	 */
	public List<String> getAccessControlAllowHeaders() {
528
		return getValuesAsList(ACCESS_CONTROL_ALLOW_HEADERS);
529 530 531 532 533 534 535 536 537 538
	}

	/**
	 * Set the (new) value of the {@code Access-Control-Allow-Methods} response header.
	 */
	public void setAccessControlAllowMethods(List<HttpMethod> allowedMethods) {
		set(ACCESS_CONTROL_ALLOW_METHODS, StringUtils.collectionToCommaDelimitedString(allowedMethods));
	}

	/**
539
	 * Return the value of the {@code Access-Control-Allow-Methods} response header.
540 541
	 */
	public List<HttpMethod> getAccessControlAllowMethods() {
542
		List<HttpMethod> result = new ArrayList<>();
543 544
		String value = getFirst(ACCESS_CONTROL_ALLOW_METHODS);
		if (value != null) {
545
			String[] tokens = StringUtils.tokenizeToStringArray(value, ",");
546
			for (String token : tokens) {
547 548 549 550
				HttpMethod resolved = HttpMethod.resolve(token);
				if (resolved != null) {
					result.add(resolved);
				}
551 552 553 554 555 556 557 558 559 560 561 562 563
			}
		}
		return result;
	}

	/**
	 * Set the (new) value of the {@code Access-Control-Allow-Origin} response header.
	 */
	public void setAccessControlAllowOrigin(String allowedOrigin) {
		set(ACCESS_CONTROL_ALLOW_ORIGIN, allowedOrigin);
	}

	/**
564
	 * Return the value of the {@code Access-Control-Allow-Origin} response header.
565 566
	 */
	public String getAccessControlAllowOrigin() {
567 568 569
		return getFieldValues(ACCESS_CONTROL_ALLOW_ORIGIN);
	}

570 571 572 573 574 575 576 577
	/**
	 * Set the (new) value of the {@code Access-Control-Expose-Headers} response header.
	 */
	public void setAccessControlExposeHeaders(List<String> exposedHeaders) {
		set(ACCESS_CONTROL_EXPOSE_HEADERS, toCommaDelimitedString(exposedHeaders));
	}

	/**
578
	 * Return the value of the {@code Access-Control-Expose-Headers} response header.
579 580
	 */
	public List<String> getAccessControlExposeHeaders() {
581
		return getValuesAsList(ACCESS_CONTROL_EXPOSE_HEADERS);
582 583 584 585 586 587 588 589 590 591
	}

	/**
	 * Set the (new) value of the {@code Access-Control-Max-Age} response header.
	 */
	public void setAccessControlMaxAge(long maxAge) {
		set(ACCESS_CONTROL_MAX_AGE, Long.toString(maxAge));
	}

	/**
592
	 * Return the value of the {@code Access-Control-Max-Age} response header.
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
	 * <p>Returns -1 when the max age is unknown.
	 */
	public long getAccessControlMaxAge() {
		String value = getFirst(ACCESS_CONTROL_MAX_AGE);
		return (value != null ? Long.parseLong(value) : -1);
	}

	/**
	 * Set the (new) value of the {@code Access-Control-Request-Headers} request header.
	 */
	public void setAccessControlRequestHeaders(List<String> requestHeaders) {
		set(ACCESS_CONTROL_REQUEST_HEADERS, toCommaDelimitedString(requestHeaders));
	}

	/**
608
	 * Return the value of the {@code Access-Control-Request-Headers} request header.
609 610
	 */
	public List<String> getAccessControlRequestHeaders() {
611
		return getValuesAsList(ACCESS_CONTROL_REQUEST_HEADERS);
612 613 614 615 616
	}

	/**
	 * Set the (new) value of the {@code Access-Control-Request-Method} request header.
	 */
617 618
	public void setAccessControlRequestMethod(HttpMethod requestMethod) {
		set(ACCESS_CONTROL_REQUEST_METHOD, requestMethod.name());
619 620 621
	}

	/**
622
	 * Return the value of the {@code Access-Control-Request-Method} request header.
623 624
	 */
	public HttpMethod getAccessControlRequestMethod() {
625
		return HttpMethod.resolve(getFirst(ACCESS_CONTROL_REQUEST_METHOD));
626 627
	}

628
	/**
J
Juergen Hoeller 已提交
629 630
	 * Set the list of acceptable {@linkplain Charset charsets},
	 * as specified by the {@code Accept-Charset} header.
631
	 */
632 633 634 635 636 637 638 639 640 641
	public void setAcceptCharset(List<Charset> acceptableCharsets) {
		StringBuilder builder = new StringBuilder();
		for (Iterator<Charset> iterator = acceptableCharsets.iterator(); iterator.hasNext();) {
			Charset charset = iterator.next();
			builder.append(charset.name().toLowerCase(Locale.ENGLISH));
			if (iterator.hasNext()) {
				builder.append(", ");
			}
		}
		set(ACCEPT_CHARSET, builder.toString());
642 643
	}

644
	/**
J
Juergen Hoeller 已提交
645 646
	 * Return the list of acceptable {@linkplain Charset charsets},
	 * as specified by the {@code Accept-Charset} header.
647 648 649 650
	 */
	public List<Charset> getAcceptCharset() {
		String value = getFirst(ACCEPT_CHARSET);
		if (value != null) {
651 652
			String[] tokens = StringUtils.tokenizeToStringArray(value, ",");
			List<Charset> result = new ArrayList<>(tokens.length);
653 654
			for (String token : tokens) {
				int paramIdx = token.indexOf(';');
655
				String charsetName;
656
				if (paramIdx == -1) {
657
					charsetName = token;
658 659
				}
				else {
660 661 662 663
					charsetName = token.substring(0, paramIdx);
				}
				if (!charsetName.equals("*")) {
					result.add(Charset.forName(charsetName));
664 665
				}
			}
666 667 668 669
			return result;
		}
		else {
			return Collections.emptyList();
670 671 672 673
		}
	}

	/**
J
Juergen Hoeller 已提交
674 675
	 * Set the set of allowed {@link HttpMethod HTTP methods},
	 * as specified by the {@code Allow} header.
676
	 */
677 678
	public void setAllow(Set<HttpMethod> allowedMethods) {
		set(ALLOW, StringUtils.collectionToCommaDelimitedString(allowedMethods));
679 680
	}

681
	/**
J
Juergen Hoeller 已提交
682 683
	 * Return the set of allowed {@link HttpMethod HTTP methods},
	 * as specified by the {@code Allow} header.
684
	 * <p>Returns an empty set when the allowed methods are unspecified.
685
	 */
686
	public Set<HttpMethod> getAllow() {
687
		String value = getFirst(ALLOW);
688
		if (!StringUtils.isEmpty(value)) {
689 690
			String[] tokens = StringUtils.tokenizeToStringArray(value, ",");
			List<HttpMethod> result = new ArrayList<>(tokens.length);
691
			for (String token : tokens) {
692 693 694 695
				HttpMethod resolved = HttpMethod.resolve(token);
				if (resolved != null) {
					result.add(resolved);
				}
696
			}
697
			return EnumSet.copyOf(result);
698 699 700 701 702 703
		}
		else {
			return EnumSet.noneOf(HttpMethod.class);
		}
	}

A
Arjen Poutsma 已提交
704
	/**
J
Juergen Hoeller 已提交
705
	 * Set the (new) value of the {@code Cache-Control} header.
A
Arjen Poutsma 已提交
706 707 708 709 710 711
	 */
	public void setCacheControl(String cacheControl) {
		set(CACHE_CONTROL, cacheControl);
	}

	/**
712
	 * Return the value of the {@code Cache-Control} header.
A
Arjen Poutsma 已提交
713 714
	 */
	public String getCacheControl() {
715
		return getFieldValues(CACHE_CONTROL);
A
Arjen Poutsma 已提交
716 717
	}

718
	/**
J
Juergen Hoeller 已提交
719
	 * Set the (new) value of the {@code Connection} header.
720 721 722 723 724 725
	 */
	public void setConnection(String connection) {
		set(CONNECTION, connection);
	}

	/**
J
Juergen Hoeller 已提交
726
	 * Set the (new) value of the {@code Connection} header.
727 728 729 730 731 732
	 */
	public void setConnection(List<String> connection) {
		set(CONNECTION, toCommaDelimitedString(connection));
	}

	/**
733
	 * Return the value of the {@code Connection} header.
734 735
	 */
	public List<String> getConnection() {
736
		return getValuesAsList(CONNECTION);
737 738
	}

739
	/**
J
Juergen Hoeller 已提交
740 741
	 * Set the (new) value of the {@code Content-Disposition} header
	 * for {@code form-data}.
742
	 * @param name the control name
J
Juergen Hoeller 已提交
743
	 * @param filename the filename (may be {@code null})
744 745
	 * @see #setContentDisposition(ContentDisposition)
	 * @see #getContentDisposition()
746 747
	 */
	public void setContentDispositionFormData(String name, String filename) {
748 749 750 751 752
		setContentDispositionFormData(name, filename, null);
	}

	/**
	 * Set the (new) value of the {@code Content-Disposition} header
753
	 * for {@code form-data}, optionally encoding the filename using the RFC 5987.
754 755 756 757
	 * <p>Only the US-ASCII, UTF-8 and ISO-8859-1 charsets are supported.
	 * @param name the control name
	 * @param filename the filename (may be {@code null})
	 * @param charset the charset used for the filename (may be {@code null})
758
	 * @since 4.3.3
759 760
	 * @see #setContentDisposition(ContentDisposition)
	 * @see #getContentDisposition()
761
	 * @see <a href="https://tools.ietf.org/html/rfc7230#section-3.2.4">RFC 7230 Section 3.2.4</a>
762 763
	 */
	public void setContentDispositionFormData(String name, String filename, Charset charset) {
764
		Assert.notNull(name, "'name' must not be null");
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
		ContentDisposition disposition = ContentDisposition.builder("form-data")
				.name(name).filename(filename, charset).build();
		setContentDisposition(disposition);
	}

	/**
	 * Set the (new) value of the {@literal Content-Disposition} header. Supports the
	 * disposition type and {@literal filename}, {@literal filename*} (encoded according
	 * to RFC 5987, only the US-ASCII, UTF-8 and ISO-8859-1 charsets are supported),
	 * {@literal name}, {@literal size} parameters.
	 * @since 5.0
	 * @see #getContentDisposition()
	 */
	public void setContentDisposition(ContentDisposition contentDisposition) {
		set(CONTENT_DISPOSITION, contentDisposition.toString());
	}

	/**
	 * Return the {@literal Content-Disposition} header parsed as a {@link ContentDisposition}
	 * instance. Supports the disposition type and {@literal filename}, {@literal filename*}
	 * (encoded according to RFC 5987, only the US-ASCII, UTF-8 and ISO-8859-1 charsets are
	 * supported), {@literal name}, {@literal size} parameters.
	 * @since 5.0
	 * @see #setContentDisposition(ContentDisposition)
	 */
	public ContentDisposition getContentDisposition() {
		String contentDisposition = getFirst(CONTENT_DISPOSITION);
		if (contentDisposition != null) {
			return ContentDisposition.parse(contentDisposition);
794
		}
795
		return ContentDisposition.empty();
796 797
	}

798 799 800 801 802
	/**
	 * Set the {@link Locale} of the content language,
	 * as specified by the {@literal Content-Language} header.
	 * <p>Use {@code set(CONTENT_LANGUAGE, ...)} if you need
	 * to set multiple content languages.</p>
R
Rossen Stoyanchev 已提交
803
	 * @since 5.0
804 805 806 807 808 809 810 811 812 813 814 815
	 */
	public void setContentLanguage(Locale locale) {
		Assert.notNull(locale, "'locale' must not be null");
		set(CONTENT_LANGUAGE, locale.toLanguageTag());
	}

	/**
	 * Return the first {@link Locale} of the content languages,
	 * as specified by the {@literal Content-Language} header.
	 * <p>Returns {@code null} when the content language is unknown.
	 * <p>Use {@code getValuesAsList(CONTENT_LANGUAGE)} if you need
	 * to get multiple content languages.</p>
R
Rossen Stoyanchev 已提交
816
	 * @since 5.0
817 818 819 820 821 822 823 824 825
	 */
	public Locale getContentLanguage() {
		return getValuesAsList(CONTENT_LANGUAGE)
				.stream()
				.findFirst()
				.map(Locale::forLanguageTag)
				.orElse(null);
	}

826
	/**
J
Juergen Hoeller 已提交
827 828
	 * Set the length of the body in bytes, as specified by the
	 * {@code Content-Length} header.
829
	 */
830 831
	public void setContentLength(long contentLength) {
		set(CONTENT_LENGTH, Long.toString(contentLength));
832 833 834
	}

	/**
J
Juergen Hoeller 已提交
835 836
	 * Return the length of the body in bytes, as specified by the
	 * {@code Content-Length} header.
837
	 * <p>Returns -1 when the content-length is unknown.
838 839 840
	 */
	public long getContentLength() {
		String value = getFirst(CONTENT_LENGTH);
841
		return (value != null ? Long.parseLong(value) : -1);
842 843 844
	}

	/**
J
Juergen Hoeller 已提交
845 846
	 * Set the {@linkplain MediaType media type} of the body,
	 * as specified by the {@code Content-Type} header.
847
	 */
848 849 850 851
	public void setContentType(MediaType mediaType) {
		Assert.isTrue(!mediaType.isWildcardType(), "'Content-Type' cannot contain wildcard type '*'");
		Assert.isTrue(!mediaType.isWildcardSubtype(), "'Content-Type' cannot contain wildcard subtype '*'");
		set(CONTENT_TYPE, mediaType.toString());
852 853 854
	}

	/**
J
Juergen Hoeller 已提交
855 856
	 * Return the {@linkplain MediaType media type} of the body, as specified
	 * by the {@code Content-Type} header.
A
Arjen Poutsma 已提交
857
	 * <p>Returns {@code null} when the content-type is unknown.
858 859 860
	 */
	public MediaType getContentType() {
		String value = getFirst(CONTENT_TYPE);
861
		return (StringUtils.hasLength(value) ? MediaType.parseMediaType(value) : null);
862 863 864
	}

	/**
J
Juergen Hoeller 已提交
865 866 867 868
	 * Set the date and time at which the message was created, as specified
	 * by the {@code Date} header.
	 * <p>The date should be specified as the number of milliseconds since
	 * January 1, 1970 GMT.
A
Arjen Poutsma 已提交
869 870 871 872 873 874
	 */
	public void setDate(long date) {
		setDate(DATE, date);
	}

	/**
J
Juergen Hoeller 已提交
875 876 877 878
	 * Return the date and time at which the message was created, as specified
	 * by the {@code Date} header.
	 * <p>The date is returned as the number of milliseconds since
	 * January 1, 1970 GMT. Returns -1 when the date is unknown.
A
Arjen Poutsma 已提交
879 880 881 882 883 884 885
	 * @throws IllegalArgumentException if the value can't be converted to a date
	 */
	public long getDate() {
		return getFirstDate(DATE);
	}

	/**
J
Juergen Hoeller 已提交
886
	 * Set the (new) entity tag of the body, as specified by the {@code ETag} header.
A
Arjen Poutsma 已提交
887 888
	 */
	public void setETag(String eTag) {
889
		if (eTag != null) {
J
Juergen Hoeller 已提交
890 891
			Assert.isTrue(eTag.startsWith("\"") || eTag.startsWith("W/"),
					"Invalid eTag, does not start with W/ or \"");
892 893
			Assert.isTrue(eTag.endsWith("\""), "Invalid eTag, does not end with \"");
		}
J
Juergen Hoeller 已提交
894
		set(ETAG, eTag);
A
Arjen Poutsma 已提交
895 896 897
	}

	/**
J
Juergen Hoeller 已提交
898
	 * Return the entity tag of the body, as specified by the {@code ETag} header.
A
Arjen Poutsma 已提交
899 900
	 */
	public String getETag() {
901
		return getFirst(ETAG);
A
Arjen Poutsma 已提交
902 903 904
	}

	/**
J
Juergen Hoeller 已提交
905 906
	 * Set the date and time at which the message is no longer valid,
	 * as specified by the {@code Expires} header.
J
Juergen Hoeller 已提交
907 908
	 * <p>The date should be specified as the number of milliseconds since
	 * January 1, 1970 GMT.
A
Arjen Poutsma 已提交
909 910 911 912 913 914
	 */
	public void setExpires(long expires) {
		setDate(EXPIRES, expires);
	}

	/**
J
Juergen Hoeller 已提交
915
	 * Return the date and time at which the message is no longer valid,
J
Juergen Hoeller 已提交
916
	 * as specified by the {@code Expires} header.
J
Juergen Hoeller 已提交
917 918
	 * <p>The date is returned as the number of milliseconds since
	 * January 1, 1970 GMT. Returns -1 when the date is unknown.
A
Arjen Poutsma 已提交
919 920
	 */
	public long getExpires() {
921
		return getFirstDate(EXPIRES, false);
A
Arjen Poutsma 已提交
922 923
	}

924 925
	/**
	 * Set the (new) value of the {@code Host} header.
J
Juergen Hoeller 已提交
926 927 928 929
	 * <p>If the given {@linkplain InetSocketAddress#getPort() port} is {@code 0},
	 * the host header will only contain the
	 * {@linkplain InetSocketAddress#getHostString() hostname}.
	 * @since 5.0
930 931
	 */
	public void setHost(InetSocketAddress host) {
J
Juergen Hoeller 已提交
932 933
		String value = (host.getPort() != 0 ?
				String.format("%s:%d", host.getHostString(), host.getPort()) : host.getHostString());
934 935 936 937 938 939 940
		set(HOST, value);
	}

	/**
	 * Return the value of the required {@code Host} header.
	 * <p>If the header value does not contain a port, the returned
	 * {@linkplain InetSocketAddress#getPort() port} will be {@code 0}.
J
Juergen Hoeller 已提交
941
	 * @since 5.0
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
	 */
	public InetSocketAddress getHost() {
		String value = getFirst(HOST);
		if (value == null) {
			return null;
		}
		int idx = value.lastIndexOf(':');
		String hostname = null;
		int port = 0;
		if (idx != -1 && idx < value.length() - 1) {
			hostname = value.substring(0, idx);
			String portString = value.substring(idx + 1);
			try {
				port = Integer.parseInt(portString);
			}
			catch (NumberFormatException ex) {
				// ignored
			}
		}
		if (hostname == null) {
			hostname = value;
		}
		return InetSocketAddress.createUnresolved(hostname, port);
	}

967 968
	/**
	 * Set the (new) value of the {@code If-Match} header.
969
	 * @since 4.3
970 971 972 973 974 975 976
	 */
	public void setIfMatch(String ifMatch) {
		set(IF_MATCH, ifMatch);
	}

	/**
	 * Set the (new) value of the {@code If-Match} header.
977
	 * @since 4.3
978 979 980 981 982 983 984
	 */
	public void setIfMatch(List<String> ifMatchList) {
		set(IF_MATCH, toCommaDelimitedString(ifMatchList));
	}

	/**
	 * Return the value of the {@code If-Match} header.
985
	 * @since 4.3
986 987 988 989 990
	 */
	public List<String> getIfMatch() {
		return getETagValuesAsList(IF_MATCH);
	}

A
Arjen Poutsma 已提交
991
	/**
J
Juergen Hoeller 已提交
992
	 * Set the (new) value of the {@code If-Modified-Since} header.
J
Juergen Hoeller 已提交
993 994
	 * <p>The date should be specified as the number of milliseconds since
	 * January 1, 1970 GMT.
A
Arjen Poutsma 已提交
995 996 997 998 999
	 */
	public void setIfModifiedSince(long ifModifiedSince) {
		setDate(IF_MODIFIED_SINCE, ifModifiedSince);
	}

1000
	/**
J
Juergen Hoeller 已提交
1001 1002 1003
	 * Return the value of the {@code If-Modified-Since} header.
	 * <p>The date is returned as the number of milliseconds since
	 * January 1, 1970 GMT. Returns -1 when the date is unknown.
1004 1005
	 */
	public long getIfModifiedSince() {
1006
		return getFirstDate(IF_MODIFIED_SINCE, false);
A
Arjen Poutsma 已提交
1007 1008
	}

A
Arjen Poutsma 已提交
1009
	/**
J
Juergen Hoeller 已提交
1010
	 * Set the (new) value of the {@code If-None-Match} header.
A
Arjen Poutsma 已提交
1011 1012
	 */
	public void setIfNoneMatch(String ifNoneMatch) {
1013
		set(IF_NONE_MATCH, ifNoneMatch);
A
Arjen Poutsma 已提交
1014 1015 1016
	}

	/**
J
Juergen Hoeller 已提交
1017
	 * Set the (new) values of the {@code If-None-Match} header.
A
Arjen Poutsma 已提交
1018 1019
	 */
	public void setIfNoneMatch(List<String> ifNoneMatchList) {
1020 1021 1022
		set(IF_NONE_MATCH, toCommaDelimitedString(ifNoneMatchList));
	}

A
Arjen Poutsma 已提交
1023
	/**
J
Juergen Hoeller 已提交
1024
	 * Return the value of the {@code If-None-Match} header.
A
Arjen Poutsma 已提交
1025 1026
	 */
	public List<String> getIfNoneMatch() {
1027
		return getETagValuesAsList(IF_NONE_MATCH);
1028 1029
	}

1030 1031 1032 1033
	/**
	 * Set the (new) value of the {@code If-Unmodified-Since} header.
	 * <p>The date should be specified as the number of milliseconds since
	 * January 1, 1970 GMT.
1034
	 * @since 4.3
1035 1036 1037 1038 1039 1040 1041 1042 1043
	 */
	public void setIfUnmodifiedSince(long ifUnmodifiedSince) {
		setDate(IF_UNMODIFIED_SINCE, ifUnmodifiedSince);
	}

	/**
	 * Return the value of the {@code If-Unmodified-Since} header.
	 * <p>The date is returned as the number of milliseconds since
	 * January 1, 1970 GMT. Returns -1 when the date is unknown.
1044
	 * @since 4.3
1045 1046 1047
	 */
	public long getIfUnmodifiedSince() {
		return getFirstDate(IF_UNMODIFIED_SINCE, false);
A
Arjen Poutsma 已提交
1048 1049 1050
	}

	/**
J
Juergen Hoeller 已提交
1051 1052 1053 1054
	 * Set the time the resource was last changed, as specified by the
	 * {@code Last-Modified} header.
	 * <p>The date should be specified as the number of milliseconds since
	 * January 1, 1970 GMT.
A
Arjen Poutsma 已提交
1055 1056 1057 1058 1059 1060
	 */
	public void setLastModified(long lastModified) {
		setDate(LAST_MODIFIED, lastModified);
	}

	/**
J
Juergen Hoeller 已提交
1061 1062 1063 1064
	 * Return the time the resource was last changed, as specified by the
	 * {@code Last-Modified} header.
	 * <p>The date is returned as the number of milliseconds since
	 * January 1, 1970 GMT. Returns -1 when the date is unknown.
A
Arjen Poutsma 已提交
1065 1066
	 */
	public long getLastModified() {
1067
		return getFirstDate(LAST_MODIFIED, false);
A
Arjen Poutsma 已提交
1068 1069 1070
	}

	/**
J
Juergen Hoeller 已提交
1071 1072
	 * Set the (new) location of a resource,
	 * as specified by the {@code Location} header.
1073
	 */
1074 1075
	public void setLocation(URI location) {
		set(LOCATION, location.toASCIIString());
1076 1077 1078
	}

	/**
J
Juergen Hoeller 已提交
1079 1080
	 * Return the (new) location of a resource
	 * as specified by the {@code Location} header.
A
Arjen Poutsma 已提交
1081
	 * <p>Returns {@code null} when the location is unknown.
1082 1083 1084
	 */
	public URI getLocation() {
		String value = getFirst(LOCATION);
1085
		return (value != null ? URI.create(value) : null);
1086 1087
	}

1088
	/**
J
Juergen Hoeller 已提交
1089
	 * Set the (new) value of the {@code Origin} header.
1090 1091 1092 1093 1094 1095
	 */
	public void setOrigin(String origin) {
		set(ORIGIN, origin);
	}

	/**
J
Juergen Hoeller 已提交
1096
	 * Return the value of the {@code Origin} header.
1097 1098 1099 1100 1101
	 */
	public String getOrigin() {
		return getFirst(ORIGIN);
	}

A
Arjen Poutsma 已提交
1102
	/**
J
Juergen Hoeller 已提交
1103
	 * Set the (new) value of the {@code Pragma} header.
A
Arjen Poutsma 已提交
1104 1105 1106 1107 1108 1109
	 */
	public void setPragma(String pragma) {
		set(PRAGMA, pragma);
	}

	/**
J
Juergen Hoeller 已提交
1110
	 * Return the value of the {@code Pragma} header.
A
Arjen Poutsma 已提交
1111 1112 1113 1114 1115
	 */
	public String getPragma() {
		return getFirst(PRAGMA);
	}

1116 1117 1118 1119 1120 1121 1122 1123 1124
	/**
	 * Sets the (new) value of the {@code Range} header.
	 */
	public void setRange(List<HttpRange> ranges) {
		String value = HttpRange.toString(ranges);
		set(RANGE, value);
	}

	/**
1125
	 * Return the value of the {@code Range} header.
1126 1127 1128 1129 1130 1131 1132
	 * <p>Returns an empty list when the range is unknown.
	 */
	public List<HttpRange> getRange() {
		String value = getFirst(RANGE);
		return HttpRange.parseRanges(value);
	}

1133
	/**
J
Juergen Hoeller 已提交
1134
	 * Set the (new) value of the {@code Upgrade} header.
1135 1136
	 */
	public void setUpgrade(String upgrade) {
R
Rossen Stoyanchev 已提交
1137
		set(UPGRADE, upgrade);
1138 1139 1140
	}

	/**
1141
	 * Return the value of the {@code Upgrade} header.
1142 1143
	 */
	public String getUpgrade() {
R
Rossen Stoyanchev 已提交
1144
		return getFirst(UPGRADE);
1145 1146
	}

1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
	/**
	 * Set the request header names (e.g. "Accept-Language") for which the
	 * response is subject to content negotiation and variances based on the
	 * value of those request headers.
	 * @param requestHeaders the request header names
	 * @since 4.3
	 */
	public void setVary(List<String> requestHeaders) {
		set(VARY, toCommaDelimitedString(requestHeaders));
	}

	/**
	 * Return the request header names subject to content negotiation.
1160
	 * @since 4.3
1161 1162
	 */
	public List<String> getVary() {
1163
		return getValuesAsList(VARY);
1164 1165
	}

1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
	/**
	 * Set the given date under the given header name after formatting it as a string
	 * using the pattern {@code "EEE, dd MMM yyyy HH:mm:ss zzz"}. The equivalent of
	 * {@link #set(String, String)} but for date headers.
	 * @since 3.2.4
	 */
	public void setDate(String headerName, long date) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMATS[0], Locale.US);
		dateFormat.setTimeZone(GMT);
		set(headerName, dateFormat.format(new Date(date)));
	}

1178
	/**
J
Juergen Hoeller 已提交
1179 1180 1181
	 * Parse the first header value for the given header name as a date,
	 * return -1 if there is no value, or raise {@link IllegalArgumentException}
	 * if the value cannot be parsed as a date.
1182 1183
	 * @param headerName the header name
	 * @return the parsed date header, or -1 if none
1184
	 * @since 3.2.4
1185 1186
	 */
	public long getFirstDate(String headerName) {
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
		return getFirstDate(headerName, true);
	}

	/**
	 * Parse the first header value for the given header name as a date,
	 * return -1 if there is no value or also in case of an invalid value
	 * (if {@code rejectInvalid=false}), or raise {@link IllegalArgumentException}
	 * if the value cannot be parsed as a date.
	 * @param headerName the header name
	 * @param rejectInvalid whether to reject invalid values with an
	 * {@link IllegalArgumentException} ({@code true}) or rather return -1
	 * in that case ({@code false})
	 * @return the parsed date header, or -1 if none (or invalid)
 	 */
	private long getFirstDate(String headerName, boolean rejectInvalid) {
A
Arjen Poutsma 已提交
1202 1203
		String headerValue = getFirst(headerName);
		if (headerValue == null) {
1204
			// No header value sent at all
A
Arjen Poutsma 已提交
1205 1206
			return -1;
		}
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
		if (headerValue.length() >= 3) {
			// Short "0" or "-1" like values are never valid HTTP date headers...
			// Let's only bother with SimpleDateFormat parsing for long enough values.
			for (String dateFormat : DATE_FORMATS) {
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US);
				simpleDateFormat.setTimeZone(GMT);
				try {
					return simpleDateFormat.parse(headerValue).getTime();
				}
				catch (ParseException ex) {
					// ignore
				}
A
Arjen Poutsma 已提交
1219 1220
			}
		}
1221 1222 1223 1224 1225
		if (rejectInvalid) {
			throw new IllegalArgumentException("Cannot parse date value \"" + headerValue +
					"\" for \"" + headerName + "\" header");
		}
		return -1;
A
Arjen Poutsma 已提交
1226 1227
	}

1228
	/**
1229 1230 1231 1232 1233
	 * Return all values of a given header name,
	 * even if this header is set multiple times.
	 * @param headerName the header name
	 * @return all associated values
	 * @since 4.3
1234
	 */
1235 1236 1237
	public List<String> getValuesAsList(String headerName) {
		List<String> values = get(headerName);
		if (values != null) {
1238
			List<String> result = new ArrayList<>();
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
			for (String value : values) {
				if (value != null) {
					String[] tokens = StringUtils.tokenizeToStringArray(value, ",");
					for (String token : tokens) {
						result.add(token);
					}
				}
			}
			return result;
		}
		return Collections.emptyList();
	}

	/**
	 * Retrieve a combined result from the field values of the ETag header.
	 * @param headerName the header name
	 * @return the combined result
	 * @since 4.3
	 */
	protected List<String> getETagValuesAsList(String headerName) {
		List<String> values = get(headerName);
		if (values != null) {
1261
			List<String> result = new ArrayList<>();
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
			for (String value : values) {
				if (value != null) {
					Matcher matcher = ETAG_HEADER_VALUE_PATTERN.matcher(value);
					while (matcher.find()) {
						if ("*".equals(matcher.group())) {
							result.add(matcher.group());
						}
						else {
							result.add(matcher.group(1));
						}
					}
					if (result.isEmpty()) {
						throw new IllegalArgumentException(
								"Could not parse header '" + headerName + "' with value '" + value + "'");
					}
				}
			}
			return result;
		}
		return Collections.emptyList();
A
Arjen Poutsma 已提交
1282
	}
1283

1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
	/**
	 * Retrieve a combined result from the field values of multi-valued headers.
	 * @param headerName the header name
	 * @return the combined result
	 * @since 4.3
	 */
	protected String getFieldValues(String headerName) {
		List<String> headerValues = get(headerName);
		return (headerValues != null ? toCommaDelimitedString(headerValues) : null);
	}

	/**
	 * Turn the given list of header values into a comma-delimited result.
	 * @param headerValues the list of header values
	 * @return a combined result with comma delimitation
	 */
	protected String toCommaDelimitedString(List<String> headerValues) {
		StringBuilder builder = new StringBuilder();
		for (Iterator<String> it = headerValues.iterator(); it.hasNext(); ) {
			String val = it.next();
			builder.append(val);
			if (it.hasNext()) {
				builder.append(", ");
			}
		}
		return builder.toString();
	}


	// MultiValueMap implementation

1315
	/**
1316
	 * Return the first header value for the given header name, if any.
1317
	 * @param headerName the header name
J
Juergen Hoeller 已提交
1318
	 * @return the first header value, or {@code null} if none
1319
	 */
1320
	@Override
1321
	public String getFirst(String headerName) {
J
Juergen Hoeller 已提交
1322 1323
		List<String> headerValues = this.headers.get(headerName);
		return (headerValues != null ? headerValues.get(0) : null);
1324 1325 1326
	}

	/**
1327
	 * Add the given, single header value under the given name.
J
Juergen Hoeller 已提交
1328
	 * @param headerName the header name
1329 1330 1331 1332 1333
	 * @param headerValue the header value
	 * @throws UnsupportedOperationException if adding headers is not supported
	 * @see #put(String, List)
	 * @see #set(String, String)
	 */
1334
	@Override
1335
	public void add(String headerName, String headerValue) {
1336 1337
		List<String> headerValues =
				this.headers.computeIfAbsent(headerName, k -> new LinkedList<>());
1338 1339 1340
		headerValues.add(headerValue);
	}

1341 1342 1343 1344 1345 1346
	@Override
	public void addAll(String key, List<String> values) {
		List<String> currentValues = this.headers.computeIfAbsent(key, k -> new LinkedList<>());
		currentValues.addAll(values);
	}

1347
	/**
1348
	 * Set the given, single header value under the given name.
J
Juergen Hoeller 已提交
1349
	 * @param headerName the header name
1350 1351 1352 1353 1354
	 * @param headerValue the header value
	 * @throws UnsupportedOperationException if adding headers is not supported
	 * @see #put(String, List)
	 * @see #add(String, String)
	 */
1355
	@Override
1356
	public void set(String headerName, String headerValue) {
1357
		List<String> headerValues = new LinkedList<>();
1358
		headerValues.add(headerValue);
J
Juergen Hoeller 已提交
1359
		this.headers.put(headerName, headerValues);
1360 1361
	}

1362
	@Override
1363 1364 1365 1366 1367 1368
	public void setAll(Map<String, String> values) {
		for (Entry<String, String> entry : values.entrySet()) {
			set(entry.getKey(), entry.getValue());
		}
	}

1369
	@Override
1370
	public Map<String, String> toSingleValueMap() {
1371
		LinkedHashMap<String, String> singleValueMap = new LinkedHashMap<>(this.headers.size());
J
Juergen Hoeller 已提交
1372
		for (Entry<String, List<String>> entry : this.headers.entrySet()) {
1373 1374 1375 1376
			singleValueMap.put(entry.getKey(), entry.getValue().get(0));
		}
		return singleValueMap;
	}
1377

J
Juergen Hoeller 已提交
1378

1379
	// Map implementation
1380

1381
	@Override
1382
	public int size() {
1383
		return this.headers.size();
1384 1385
	}

1386
	@Override
1387
	public boolean isEmpty() {
1388
		return this.headers.isEmpty();
1389 1390
	}

1391
	@Override
1392
	public boolean containsKey(Object key) {
1393
		return this.headers.containsKey(key);
1394 1395
	}

1396
	@Override
1397
	public boolean containsValue(Object value) {
1398
		return this.headers.containsValue(value);
1399 1400
	}

1401
	@Override
1402
	public List<String> get(Object key) {
1403
		return this.headers.get(key);
1404 1405
	}

1406
	@Override
1407
	public List<String> put(String key, List<String> value) {
1408
		return this.headers.put(key, value);
1409 1410
	}

1411
	@Override
1412
	public List<String> remove(Object key) {
1413
		return this.headers.remove(key);
1414 1415
	}

1416
	@Override
J
Juergen Hoeller 已提交
1417 1418
	public void putAll(Map<? extends String, ? extends List<String>> map) {
		this.headers.putAll(map);
1419 1420
	}

1421
	@Override
1422
	public void clear() {
1423
		this.headers.clear();
1424 1425
	}

1426
	@Override
1427
	public Set<String> keySet() {
1428
		return this.headers.keySet();
1429 1430
	}

1431
	@Override
1432
	public Collection<List<String>> values() {
1433
		return this.headers.values();
1434 1435
	}

1436
	@Override
1437
	public Set<Entry<String, List<String>>> entrySet() {
1438
		return this.headers.entrySet();
1439 1440
	}

1441

1442
	@Override
1443 1444
	public boolean equals(Object other) {
		if (this == other) {
1445 1446
			return true;
		}
1447 1448
		if (!(other instanceof HttpHeaders)) {
			return false;
1449
		}
1450 1451 1452 1453 1454 1455 1456
		HttpHeaders otherHeaders = (HttpHeaders) other;
		return this.headers.equals(otherHeaders.headers);
	}

	@Override
	public int hashCode() {
		return this.headers.hashCode();
1457 1458 1459 1460
	}

	@Override
	public String toString() {
1461
		return this.headers.toString();
1462
	}
1463

J
Juergen Hoeller 已提交
1464 1465 1466 1467 1468 1469 1470 1471

	/**
	 * Return a {@code HttpHeaders} object that can only be read, not written to.
	 */
	public static HttpHeaders readOnlyHttpHeaders(HttpHeaders headers) {
		return new HttpHeaders(headers, true);
	}

1472
}