Content-type explanations in HTTP requests and their application in spring MVC

Source: Internet
Author: User
Tags class definition ranges

Introduction: in HTTP requests, we use Content-type every day to specify different formats of request information, but few people have a thorough understanding of how many values are allowed in content-type, and this will explain Content-type available values, as well as the spring How they are used in MVC to map request Information.

1. content-type

mediatype, which is the Internet media type, the Internet medium, or the MIME type, in the HTTP protocol message header, uses Content-type to represent the media type information in the specific Request.

[html]View PlainCopy 
    1. Type format: type/subtype (;p arameter)? Type
    2. The main type, arbitrary string, such as text, if the * number represents all;
    3. Subtype subtype, arbitrary string, such as html, if the * number represents all;
    4. Parameter optional, some parameters, such as the Q parameter of the Accept request header, Content-type the CharSet parameter.

For Example: content-type:text/html;charset:utf-8;

The common media format types are as Follows:

    • text/html:html format
    • Text/plain: Plain Text Format
    • Text/xml:xml format
    • Image/gif:gif Picture Format
    • Image/jpeg:jpg Picture Format
    • Image/png:png Picture Format

Types of media formats that start with application:

    • application/xhtml+xml:xhtml format
    • Application/xml:xml data format
    • Application/atom+xml:atom XML Aggregation format
    • Application/json:json data format
    • Application/pdf:pdf format
    • Application/msword:word Document Format
    • Application/octet-stream: binary stream Data (e.g., common file Downloads)
    • Application/x-www-form-urlencoded: <form enctype= "" > Default enctype,form form data is encoded as key/ The value format is sent to the server (the format of the Form's default submission Data)

Another common media format is used when uploading files:

    • Multipart/form-data: when you need to upload a file in a form, you need to use that format

These are some of the content-type content formats that we often use in our daily Development.

2. About the use of Content-type type information in Spring MVC

first, let's look at the class definition in requestmapping:

[html]View PlainCopy 
  1. @Target ({elementtype.method, Elementtype.type})
  2. @Retention (retentionpolicy.runtime)
  3. @Documented
  4. @Mapping
  5. Public @interface requestmapping {
  6. string[] value () default {};
  7. requestmethod[] method () Default {};
  8. string[] params () default {};
  9. string[] headers () Default {};
  10. string[] consumes () default {};
  11. String[] produces () default {};
  12. }

value: specifies the actual address of the request, such as/action/info.
method: Specifies the type of method requested, GET, POST, PUT, delete, etc.
consumes: Specifies the type of submission to process the request (content-type), such as application/json, text/html;
produces: Specifies the type of content returned, only if the type in the request header (Accept) contains the specified type to return
Params: specifies that certain parameter values must be included in the request for the method to process
Headers: specifies that certain header values must be included in the request in order for the method to process requests

Among them, consumes, produces use Content-typ information to filter information, headers can use Content-type to filter and Judge.

3. Using the example

3.1 Headers

[html]View PlainCopy 
    1. @RequestMapping (value = "/test", method = requestmethod.get, headers="referer=http:// Www.ifeng.com/")
    2. public void Testheaders (@PathVariable string ownerid, @PathVariable string Petid) {
    3. Implementation omitted
    4. }

The headers inside can match all the information that can appear in the header, not limited to the Referer Information.

Example 2

[html]View PlainCopy 
  1. @RequestMapping (value = "/response/contenttype", headers = "accept=application/json")
  2. public void Response2 (httpservletresponse Response) throws IOException {
  3. The media type that represents the content area data for the response is in JSON format and is encoded as Utf-8 (the client should decode with UTF-8)
  4. Response.setcontenttype ("application/json;     charset=Utf-8 ");
  5. Write out the response body content
  6. String jsondata = "{\"username\ ": \" zhang\ ", \" password\ ": \" 123\ "}";
  7. Response.getwriter (). Write (jsondata);
  8. }

The server produces JSON data based on the request header "accept=application/json".

When you have the following accept header, you will follow the following rules to apply:
①accept:text/html,application/xml,application/json
The produces matching is performed in the following order ①text/html②application/xml③application/json
②accept:application/xml;q=0.5,application/json;q=0.9,text/html
The produces matching is performed in the following order ①text/html②application/json③application/xml
parameter is the mass factor of the media type, the higher the priority (from 0 to 1)
③accept:*/*,text/*,text/html
The produces matching is performed in the following order ①text/html②text/*③*/*


That is, the matching rule is: the most explicit priority Match.

Requests part
Header explain Example
Accept Specify what types of content clients can receive accept:text/plain, text/html
Accept-charset The set of character encodings that the browser can Accept. Accept-charset:iso-8859-5
Accept-encoding Specifies that the Web server that the browser can support returns the content compression encoding Type. accept-encoding:compress, gzip
Accept-language Browser-acceptable language Accept-language:en,zh
Accept-ranges You can request one or more child range fields for a Web page entity Accept-ranges:bytes
Authorization Authorization Certificate for HTTP Authorization Authorization:basic qwxhzgrpbjpvcgvuihnlc2ftzq==
Cache-control Specify the caching mechanism that requests and responses follow Cache-control:no-cache
Connection Indicates whether a persistent connection is Required. (HTTP 1.1 defaults to persistent Connection) Connection:close
Cookies When an HTTP request is sent, all cookie values stored under that request domain are sent to the web Server. Cookie: $Version = 1; skin=new;
Content-length The requested content length content-length:348
Content-type The requested MIME information corresponding to the entity content-type:application/x-www-form-urlencoded
Date Date and time the request was sent date:tue, 08:12:31 GMT
Expect The specific server behavior of the request Expect:100-continue
From Email from the user who made the request From: [email protected]
Host Specify the domain name and port number of the requested server Host:www.zcmhi.com
If-match Only valid if the request content matches the entity If-match: "737060cd8c284d8af7ad3082f209582d"
If-modified-since If the requested part is modified after the specified time, the request succeeds, and the 304 code is returned without modification if-modified-since:sat, Oct 19:43:31 GMT
If-none-match If the content does not change the return 304 code, The parameter is the Server's previously sent etag, and the server responded to the ETag comparison to determine whether the change If-none-match: "737060cd8c284d8af7ad3082f209582d"
If-range If the entity does not change, the server sends the missing portion of the client, otherwise the entire entity is Sent. The parameters are also ETag If-range: "737060cd8c284d8af7ad3082f209582d"
If-unmodified-since Request succeeds only if the entity has not been modified since the specified time if-unmodified-since:sat, Oct 19:43:31 GMT
Max-forwards Limit the time that information is transmitted through agents and gateways Max-forwards:10
Pragma Used to include implementation-specific instructions Pragma:no-cache
Proxy-authorization Connect to an authorization certificate for the agent Proxy-authorization:basic qwxhzgrpbjpvcgvuihnlc2ftzq==
Range Request only part of an entity, specify a range range:bytes=500-999
Referer The address of the previous page, which is immediately followed by the current request page, Referer:http://www.zcmhi.com/archives/71.html
TE The client is willing to accept the transfer encoding and notifies the server to accept the trailing header information te:trailers,deflate;q=0.5
Upgrade Specify some kind of transport protocol to the server for the server to convert (if supported) upgrade:http/2.0, shttp/1.3, irc/6.9, rta/x11
User-agent The content of the user-agent contains the user information that made the request user-agent:mozilla/5.0 (Linux; X11)
Via Notifies the intermediary gateway or proxy Server address, communication protocol via:1.0 fred, 1.1 nowhere.com (apache/1.1)
Warning About warning messages for message entities warn:199 Miscellaneous Warning
Responses part
Header explain Example
Accept-ranges Indicates whether the server supports the specified range request and what kind of staging request Accept-ranges:bytes
Age Estimated time (in seconds, non-negative) from the original server to the proxy cache Age:12
Allow A valid request behavior for a network resource is not allowed to return 405 allow:get, HEAD
Cache-control Tell if all caching mechanisms can be cached and which type Cache-control:no-cache
Content-encoding The type of return content compression encoding supported by the Web Server. Content-encoding:gzip
Content-language The language of the response body Content-language:en,zh
Content-length The length of the response body content-length:348
Content-location Alternate alternative address to request resource substitution Content-location:/index.htm
Content-md5 Returns the MD5 checksum value of a resource content-md5:q2hly2sgsw50zwdyaxr5iq==
Content-range The byte position of this section in the entire return body Content-range:bytes 21010-47021/47022
Content-type Returns the MIME type of the content content-type:text/html; Charset=utf-8
Date Time the original server message was issued date:tue, 08:12:31 GMT
ETag The current value of the entity label of the request variable ETag: "737060cd8c284d8af7ad3082f209582d"
Expires Date and time when the response expires expires:thu, 16:00:00 GMT
Last-modified Requested last modified time for resource last-modified:tue, 12:45:26 GMT
Location Used to redirect the receiver to the location of the Non-request URL to complete the request or identify the new resource Location:http://www.zcmhi.com/archives/94.html
Pragma Includes implementing a specific instruction that can be applied to any receiver on the response chain Pragma:no-cache
Proxy-authenticate It indicates the authentication scheme and the parameters on the URL that can be applied to the proxy Proxy-authenticate:basic
Refresh Applied to redirect or a new resource was created, redirected after 5 seconds (proposed by netscape, supported by most Browsers)

refresh:5; Url=http://www.zcmhi.com/archives/94.html

Retry-after Notifies the client to try again after a specified time if the entity is temporarily undesirable retry-after:120
Server Web Server Software Name server:apache/1.3.27 (Unix) (red-hat/linux)
Set-cookie Set HTTP Cookies set-cookie:userid=johndoe; max-age=3600; Version=1
Trailer Indicates that the header domain is present at the end of the chunked transfer code Trailer:max-forwards
Transfer-encoding File transfer encoding Transfer-encoding:chunked
Vary Tells the downstream agent whether to use the cache response or request from the original server Vary: *
Via Tells the proxy client where the response was sent by via:1.0 fred, 1.1 nowhere.com (apache/1.1)
Warning Warning about possible issues with the entity warning:199 Miscellaneous Warning
Www-authenticate Indicates the authorization scheme that the client request entity should use Www-authenticate:basic

Example of 3.2 params

[html]View PlainCopy 
    1. @RequestMapping (value = "/test/{userid}", method = requestmethod.get, params="myparam= MyValue ")
    2. public void Finduser (@PathVariable String userId) {
    3. Implementation omitted
    4. }

A request with the name "myparam" and a value of "myvalue" is included in the processing request, which acts as a filter.

3.3 Consumes/produces

[html]View PlainCopy 
  1. @Controller
  2. @RequestMapping (value = "/users", method = requestmethod.post, consumes="application/json" , produces="application/json")
  3. @ResponseBody
  4. Public List<user> AddUser (@RequestBody user userl) {
  5. Implementation omitted
  6. return List<User> users;
  7. }

The Content-type method only processes requests with the request "application/json" Type. The produces identity ==> handles the request that contains "application/json" in the Accept header of the request, and implies that the returned content type is application/json;

4. Summary

In this article, we first introduced the main supported format content of content-type, and then introduced the main use method based on the content of @requestmapping annotation, in which, headers, consumes,produces, Is the use of content-type in the various media format content, can be based on this format content for access control and Filtering.

Content-type explained in HTTP requests and applications in spring MVC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.