- Class HttpHeaders
- Nested Class Summary
- Nested classes/interfaces inherited from interface java.util.Map
- Field Summary
- Constructor Summary
- Method Summary
- Methods inherited from class java.lang.Object
- Methods inherited from interface java.util.Map
- Methods inherited from interface org.springframework.util.MultiValueMap
- Field Details
- ACCEPT
- ACCEPT_CHARSET
- ACCEPT_ENCODING
- ACCEPT_LANGUAGE
- ACCEPT_PATCH
- ACCEPT_RANGES
- ACCESS_CONTROL_ALLOW_CREDENTIALS
- ACCESS_CONTROL_ALLOW_HEADERS
- ACCESS_CONTROL_ALLOW_METHODS
- ACCESS_CONTROL_ALLOW_ORIGIN
- ACCESS_CONTROL_EXPOSE_HEADERS
- ACCESS_CONTROL_MAX_AGE
- ACCESS_CONTROL_REQUEST_HEADERS
- ACCESS_CONTROL_REQUEST_METHOD
- AGE
- ALLOW
- AUTHORIZATION
- CACHE_CONTROL
- CONNECTION
- CONTENT_ENCODING
- CONTENT_DISPOSITION
- CONTENT_LANGUAGE
- CONTENT_LENGTH
- CONTENT_LOCATION
- CONTENT_RANGE
- CONTENT_TYPE
- COOKIE
- DATE
- ETAG
- EXPECT
- EXPIRES
- FROM
- HOST
- IF_MATCH
- IF_MODIFIED_SINCE
- IF_NONE_MATCH
- IF_RANGE
- IF_UNMODIFIED_SINCE
- LAST_MODIFIED
- LINK
- LOCATION
- MAX_FORWARDS
- ORIGIN
- PRAGMA
- PROXY_AUTHENTICATE
- PROXY_AUTHORIZATION
- RANGE
- REFERER
- RETRY_AFTER
- SERVER
- SET_COOKIE
- SET_COOKIE2
- TE
- TRAILER
- TRANSFER_ENCODING
- UPGRADE
- USER_AGENT
- VARY
- VIA
- WARNING
- WWW_AUTHENTICATE
- EMPTY
- Constructor Details
- HttpHeaders
- HttpHeaders
- Method Details
- getOrEmpty
- setAccept
- getAccept
- setAcceptLanguage
- getAcceptLanguage
- setAcceptLanguageAsLocales
- getAcceptLanguageAsLocales
- setAcceptPatch
- getAcceptPatch
- setAccessControlAllowCredentials
- getAccessControlAllowCredentials
- setAccessControlAllowHeaders
- getAccessControlAllowHeaders
- setAccessControlAllowMethods
- getAccessControlAllowMethods
- setAccessControlAllowOrigin
- getAccessControlAllowOrigin
- setAccessControlExposeHeaders
- getAccessControlExposeHeaders
- setAccessControlMaxAge
- setAccessControlMaxAge
- getAccessControlMaxAge
- setAccessControlRequestHeaders
- getAccessControlRequestHeaders
- setAccessControlRequestMethod
- getAccessControlRequestMethod
- setAcceptCharset
- getAcceptCharset
- setAllow
- getAllow
- setBasicAuth
- setBasicAuth
- setBasicAuth
- setBearerAuth
- setCacheControl
- setCacheControl
- getCacheControl
- setConnection
- setConnection
- getConnection
- setContentDispositionFormData
- setContentDisposition
- getContentDisposition
- setContentLanguage
- getContentLanguage
- setContentLength
- getContentLength
- setContentType
- getContentType
- setDate
- setDate
- setDate
- getDate
- setETag
- getETag
- setExpires
- setExpires
- setExpires
- getExpires
- setHost
- getHost
- Java – HTTP headers encoding/decoding in Java
- Best Solution
- Related Solutions
Class HttpHeaders
A data structure representing HTTP request or response headers, mapping String header names to a list of String values, also offering accessors for common application-level data types.
- getFirst(String) returns the first value associated with a given header name
- add(String, String) adds a header value to the list of values for a header name
- set(String, String) sets the header value to a single string value
Note that HttpHeaders generally treats header names in a case-insensitive manner.
Nested Class Summary
Nested classes/interfaces inherited from interface java.util.Map
Field Summary
Constructor Summary
Method Summary
Helps to format HTTP header values, as HTTP header values themselves can contain comma-separated values, can become confusing with regular Map formatting that also uses commas between entries.
Return the list of acceptable media types for PATCH methods, as specified by the Accept-Patch header.
Return the date and time at which the message is no longer valid, as specified by the Expires header.
Parse the first header value for the given header name as a date, return -1 if there is no value, or raise IllegalArgumentException if the value cannot be parsed as a date.
Parse the first header value for the given header name as a date, return null if there is no value, or raise IllegalArgumentException if the value cannot be parsed as a date.
Set the value of the Authorization header to Basic Authentication based on the given encoded credentials.
Set the value of the Authorization header to Basic Authentication based on the given username and password.
Set the value of the Authorization header to Basic Authentication based on the given username and password.
Set the given date under the given header name after formatting it as a string using the RFC-1123 date-time formatter.
Set the given date under the given header name after formatting it as a string using the RFC-1123 date-time formatter.
Set the given date under the given header name after formatting it as a string using the RFC-1123 date-time formatter.
Remove any read-only wrapper that may have been previously applied around the given headers via readOnlyHttpHeaders(HttpHeaders) .
Methods inherited from class java.lang.Object
Methods inherited from interface java.util.Map
Methods inherited from interface org.springframework.util.MultiValueMap
Field Details
ACCEPT
ACCEPT_CHARSET
ACCEPT_ENCODING
ACCEPT_LANGUAGE
ACCEPT_PATCH
ACCEPT_RANGES
ACCESS_CONTROL_ALLOW_CREDENTIALS
ACCESS_CONTROL_ALLOW_HEADERS
ACCESS_CONTROL_ALLOW_METHODS
ACCESS_CONTROL_ALLOW_ORIGIN
ACCESS_CONTROL_EXPOSE_HEADERS
ACCESS_CONTROL_MAX_AGE
ACCESS_CONTROL_REQUEST_HEADERS
ACCESS_CONTROL_REQUEST_METHOD
AGE
ALLOW
AUTHORIZATION
CACHE_CONTROL
CONNECTION
CONTENT_ENCODING
CONTENT_DISPOSITION
CONTENT_LANGUAGE
CONTENT_LENGTH
CONTENT_LOCATION
CONTENT_RANGE
CONTENT_TYPE
COOKIE
DATE
ETAG
EXPECT
EXPIRES
FROM
HOST
IF_MATCH
IF_MODIFIED_SINCE
IF_NONE_MATCH
IF_RANGE
IF_UNMODIFIED_SINCE
LAST_MODIFIED
LINK
LOCATION
MAX_FORWARDS
ORIGIN
PRAGMA
PROXY_AUTHENTICATE
PROXY_AUTHORIZATION
RANGE
REFERER
RETRY_AFTER
SERVER
SET_COOKIE
SET_COOKIE2
TE
TRAILER
TRANSFER_ENCODING
UPGRADE
USER_AGENT
VARY
VIA
WARNING
WWW_AUTHENTICATE
EMPTY
Constructor Details
HttpHeaders
Construct a new, empty instance of the HttpHeaders object. This is the common constructor, using a case-insensitive map structure.
HttpHeaders
Construct a new HttpHeaders instance backed by an existing map. This constructor is available as an optimization for adapting to existing headers map structures, primarily for internal use within the framework.
Method Details
getOrEmpty
setAccept
getAccept
Return the list of acceptable media types, as specified by the Accept header. Returns an empty list when the acceptable media types are unspecified.
setAcceptLanguage
getAcceptLanguage
Return the language ranges from the «Accept-Language» header. If you only need sorted, preferred locales only use getAcceptLanguageAsLocales() or if you need to filter based on a list of supported locales you can pass the returned list to Locale.filter(List, Collection) .
setAcceptLanguageAsLocales
getAcceptLanguageAsLocales
setAcceptPatch
getAcceptPatch
Return the list of acceptable media types for PATCH methods, as specified by the Accept-Patch header. Returns an empty list when the acceptable media types are unspecified.
setAccessControlAllowCredentials
getAccessControlAllowCredentials
setAccessControlAllowHeaders
getAccessControlAllowHeaders
setAccessControlAllowMethods
getAccessControlAllowMethods
setAccessControlAllowOrigin
getAccessControlAllowOrigin
setAccessControlExposeHeaders
getAccessControlExposeHeaders
setAccessControlMaxAge
setAccessControlMaxAge
getAccessControlMaxAge
Return the value of the Access-Control-Max-Age response header. Returns -1 when the max age is unknown.
setAccessControlRequestHeaders
getAccessControlRequestHeaders
setAccessControlRequestMethod
getAccessControlRequestMethod
setAcceptCharset
getAcceptCharset
setAllow
getAllow
Return the set of allowed HTTP methods , as specified by the Allow header. Returns an empty set when the allowed methods are unspecified.
setBasicAuth
Set the value of the Authorization header to Basic Authentication based on the given username and password. Note that this method only supports characters in the ISO-8859-1 character set.
setBasicAuth
Set the value of the Authorization header to Basic Authentication based on the given username and password.
setBasicAuth
Set the value of the Authorization header to Basic Authentication based on the given encoded credentials. Favor this method over setBasicAuth(String, String) and setBasicAuth(String, String, Charset) if you wish to cache the encoded credentials.
setBearerAuth
setCacheControl
setCacheControl
getCacheControl
setConnection
setConnection
getConnection
setContentDispositionFormData
Set the Content-Disposition header when creating a «multipart/form-data» request. Applications typically would not set this header directly but rather prepare a MultiValueMap
setContentDisposition
Set the Content-Disposition header. This could be used on a response to indicate if the content is expected to be displayed inline in the browser or as an attachment to be saved locally. It can also be used for a «multipart/form-data» request. For more details see notes on setContentDispositionFormData(java.lang.String, java.lang.String) .
getContentDisposition
setContentLanguage
Set the Locale of the content language, as specified by the Content-Language header. Use put(CONTENT_LANGUAGE, list) if you need to set multiple content languages.
getContentLanguage
Get the first Locale of the content languages, as specified by the Content-Language header. Use getValuesAsList(String) if you need to get multiple content languages.
setContentLength
getContentLength
Return the length of the body in bytes, as specified by the Content-Length header. Returns -1 when the content-length is unknown.
setContentType
getContentType
Return the media type of the body, as specified by the Content-Type header. Returns null when the Content-Type header is not set.
setDate
setDate
setDate
Set the date and time at which the message was created, as specified by the Date header. The date should be specified as the number of milliseconds since January 1, 1970 GMT.
getDate
Return the date and time at which the message was created, as specified by the Date header. The date is returned as the number of milliseconds since January 1, 1970 GMT. Returns -1 when the date is unknown.
setETag
getETag
setExpires
setExpires
setExpires
Set the date and time at which the message is no longer valid, as specified by the Expires header. The date should be specified as the number of milliseconds since January 1, 1970 GMT.
getExpires
Return the date and time at which the message is no longer valid, as specified by the Expires header. The date is returned as the number of milliseconds since January 1, 1970 GMT. Returns -1 when the date is unknown.
setHost
Set the (new) value of the Host header. If the given port is 0 , the host header will only contain the host name.
getHost
Return the value of the Host header, if available. If the header value does not contain a port, the port in the returned address will be 0 .
Java – HTTP headers encoding/decoding in Java
A custom HTTP header is being passed to a Servlet application for authentication purposes. The header value must be able to contain accents and other non-ASCII characters, so must be in a certain encoding (ideally UTF-8).
I am provided with this piece of Java code by the developers who control the authentication environment:
String firstName = request.getHeader("my-custom-header"); String decodedFirstName = new String(firstName.getBytes(),"UTF-8");
But this code doesn’t look right to me: it presupposes the encoding of the header value, when it seemed to me that there was a proper way of specifying an encoding for header values (from MIME I believe).
Here is my question: what is the right way ™ of dealing with custom header values that need to support a UTF-8 encoding:
- on the wire (how the header looks like over the wire)
- from the decoding point of view (how to decode it using the Java Servlet API, and can we assume that request.getHeader() already properly does the decoding)
Here is an environment independent code sample to treat headers as UTF-8 in case you can’t change your service:
String valueAsISO = request.getHeader("my-custom-header"); String valueAsUTF8 = new String(firstName.getBytes("ISO8859-1"),"UTF-8");
Best Solution
Again: RFC 2047 is not implemented in practice. The next revision of HTTP/1.1 is going to remove any mention of it.
So, if you need to transport non-ASCII characters, the safest way is to encode them into a sequence of ASCII, such as the «Slug» header in the Atom Publishing Protocol.
Related Solutions
Java – What are the differences between a HashMap and a Hashtable in Java
There are several differences between HashMap and Hashtable in Java:
- Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
- Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
- One of HashMap’s subclasses is LinkedHashMap , so in the event that you’d want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap . This wouldn’t be as easy if you were using Hashtable .
Since synchronization is not an issue for you, I’d recommend HashMap . If synchronization becomes an issue, you may also look at ConcurrentHashMap .
Java – Is Java “pass-by-reference” or “pass-by-value”
Java is always pass-by-value. Unfortunately, when we deal with objects we are really dealing with object-handles called references which are passed-by-value as well. This terminology and semantics easily confuse many beginners.
public static void main(String[] args) < Dog aDog = new Dog("Max"); Dog oldDog = aDog; // we pass the object to foo foo(aDog); // aDog variable is still pointing to the "Max" dog when foo(. ) returns aDog.getName().equals("Max"); // true aDog.getName().equals("Fifi"); // false aDog == oldDog; // true >public static void foo(Dog d) < d.getName().equals("Max"); // true // change d inside of foo() to point to a new Dog instance "Fifi" d = new Dog("Fifi"); d.getName().equals("Fifi"); // true >
In the example above aDog.getName() will still return «Max» . The value aDog within main is not changed in the function foo with the Dog «Fifi» as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return «Fifi» after the call to foo .
public static void main(String[] args) < Dog aDog = new Dog("Max"); Dog oldDog = aDog; foo(aDog); // when foo(. ) returns, the name of the dog has been changed to "Fifi" aDog.getName().equals("Fifi"); // true // but it is still the same dog: aDog == oldDog; // true >public static void foo(Dog d) < d.getName().equals("Max"); // true // this changes the name of d to be "Fifi" d.setName("Fifi"); >
In the above example, Fifi is the dog’s name after call to foo(aDog) because the object’s name was set inside of foo(. ) . Any operations that foo performs on d are such that, for all practical purposes, they are performed on aDog , but it is not possible to change the value of the variable aDog itself.
For more information on pass by reference and pass by value, consult the following SO answer: https://stackoverflow.com/a/430958/6005228. This explains more thoroughly the semantics and history behind the two and also explains why Java and many other modern languages appear to do both in certain cases.