Accept and Content Type Headers

Accept and Content Type Headers

In HTTP requests, headers play a crucial role in specifying details about the request or response. Two important headers used in HTTP requests are  Accept  and  Content-Type.

Accept and Content Type Headers

Accept Header

The  Accept  header is used by HTTP clients to specify the media types (MIME types) that are acceptable for the response. It tells the server what kind of response formats the client can process. The server then selects one of the media types that it supports and returns the response in that format.

Examples of media types :

  • text/html
  • application/json
  • application/xml
  • image/png

Content-Type Header

The  Content-Type  header is used to indicate the media type of the resource or the data being sent to the server. It tells the server what the format of the request body is so that it can parse it correctly.

Examples of media types :

  • application/json
  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

Explanation in Java Example

Let’s consider a simple RESTful web service example using Java with Jersey, demonstrating how to use the Accept and Content-Type headers.

Maven Dependencies (pom.xml)
xml
<dependencies>
    <dependency>
        <groupId>javax.ws.rs</groupId>
        <artifactId>javax.ws.rs-api</artifactId>
        <version>2.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>2.29.1</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>2.29.1</version>
    </dependency>
</dependencies>

RESTful Service Endpoint (BookResource.java)
java
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.Map;

@Path("/books")
public class BookResource {

    private static Map<Integer, Book> bookStore = new HashMap<>();

    @GET
    @Path("/{id}")
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public Response getBook(@PathParam("id") int id, @HeaderParam("Accept") String acceptHeader) {
        Book book = bookStore.get(id);
        if (book == null) {
            return Response.status(Response.Status.NOT_FOUND).entity("Book not found").build();
        }
        return Response.ok(book).type(acceptHeader).build();
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response createBook(Book book) {
        bookStore.put(book.getId(), book);
        return Response.status(Response.Status.CREATED).entity(book).build();
    }

    static {
        bookStore.put(1, new Book(1, "Java Programming", "John Doe"));
        bookStore.put(2, new Book(2, "RESTful Web Services", "Jane Doe"));
    }
}

Book Class (Book.java)
java
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Book {
    private int id;
    private String title;
    private String author;

    public Book() {}

    public Book(int id, String title, String author) {
        this.id = id;
        this.title = title;
        this.author = author;
    }

    // Getters and Setters
}

Application Config Class (RestApplication.java)
java
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/api")
public class RestApplication extends Application {
    // No need to implement any methods
}

web.xml Configuration
xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <display-name>BookApp</display-name>

    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.example.RestApplication</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>

</web-app>

Explanation

  • 1.  Accept Header :
    • When a client sends a GET request to /books/{id} with an Accept header of application/json, the server responds with the book data in JSON format.
    • If the Accept header is application/xml, the server responds with the book data in XML format.
  • 2.  Content-Type Header :
    • When a client sends a POST request to /books with a Content-Type header of application/json, the server knows that the request body is in JSON format and parses it accordingly to create a new book.