Showing posts with label HTTP Headers. Show all posts
Showing posts with label HTTP Headers. Show all posts

Monday, 12 April 2021

HTTP Headers: Accept and Content-Type - RESTful Web Services with Spring framework | Spring Boot

🚀 Build Smarter APIs!

Subscribe to Ram N Java for simplified Java, Spring Boot, and REST API tutorials!

SUBSCRIBE TO OUR CHANNEL

Mastering HTTP Headers: Accept & Content-Type

Understanding how a client and server communicate their data preferences is vital for any professional RESTful Web Service. In this tutorial, we demystify the two most important HTTP headers: Accept and Content-Type.

The Language of API Communication

Think of HTTP headers as the "negotiation" phase between your frontend and backend. We break down exactly how these headers function in a Spring Boot environment:

  • Content-Type: Learn how this header tells the server the format of the data being sent (e.g., JSON or XML).
  • Accept: Discover how the client uses this header to tell the server what format it wants to receive in return.
  • Media Types: Understanding standard types like application/json and application/xml.

Live Testing with Postman

We show you how to manually set these headers in Postman to see Content Negotiation in action. You'll observe how the server responds differently based on the headers you provide, making your APIs flexible and client-friendly.

Why This Matters

Properly handling headers is a core principle of REST architecture. It allows your Spring Framework applications to be interoperable with various clients, from web browsers to mobile apps and other microservices. Mastering this ensures your data is always delivered in the correct format.

📥 Get the Source Code!

I have shared the full source code and PowerPoint presentation for this headers tutorial! Check out the download links in the YouTube video description above.

Friday, 12 February 2021

HTTP headers: Content-Type header | Web Services Tutorial

🚀 Ready to Master REST APIs? 🚀

Join the Ram N Java community for the best step-by-step tech tutorials that simplify your coding journey!

SUBSCRIBE NOW

Understanding the Content-Type Header

When two computers talk to each other over the internet, they need to agree on what language they are speaking. The Content-Type Header is the tool we use to make that happen. Without it, a server might receive data but have no idea how to read it.

What is Content-Type?

The Content-Type header tells the receiver (the server or the browser) the media type of the data being sent in the HTTP body. It’s like a label on a box that says "Fragile" or "Books"—it tells the receiver exactly what to expect inside the package.

Common Content Types

In modern web development and REST APIs, you will see these types almost every day:

  • application/json: The most popular choice for APIs. It sends data as a structured JavaScript object.
  • text/html: Used when the server is sending back a full web page to be rendered by your browser.
  • application/xml: An older but very structured format often used in enterprise systems.
  • multipart/form-data: Used when you are uploading files, like images or documents, via a web form.

Why Is It So Important?

If you send a JSON body but forget to set the Content-Type to application/json, the server might try to read it as plain text and fail. This is a very common cause of bugs for beginners! Always double-check your headers to ensure smooth communication between your frontend and backend.

Check Out More From My Channel

Enhance your skills with these other helpful tutorials from Ram N Java:

Sunday, 4 May 2014

Servlets : Display HTTP Request and Response headers

🚀 Master Java Servlets & Web Development!

Subscribe to Ram N Java for clean, beginner-friendly coding tutorials and practical web architecture guides!

👉 Click Here to Subscribe Now

What Are HTTP Request and Response Headers?

Whenever a browser communicates with a web server, it sends HTTP headers containing critical metadata such as browser specifications, supported MIME types, compression encodings, host information, and cookies. Similarly, the server returns response headers providing information about content type, date, caching instructions, and status codes.

In Java Servlets, inspecting these headers allows you to build smarter applications—such as serving different assets based on the client browser, inspecting user language preferences, or debugging communication protocols.

Step 1: Reading Request Headers in HttpServlet

The HttpServletRequest interface provides dedicated methods to retrieve header names and values:

  • getHeaderNames(): Returns an Enumeration<String> containing all header names sent by the browser.
  • getHeader(String name): Returns the value of a specific header as a String.
  • getHeaders(String name): Returns an Enumeration<String> for headers that contain multiple values.
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
  String headerName = headerNames.nextElement();
  String headerValue = request.getHeader(headerName);
  out.println(headerName + " : " + headerValue + "<br>");
}

Step 2: Setting & Inspecting Response Headers

You can customize response headers using HttpServletResponse before committing output to the browser:

// Setting custom and standard headers
response.setContentType("text/html");
response.setHeader("Custom-Header", "JavaServletDemo");
response.setDateHeader("Expires", System.currentTimeMillis() + 60000);

// Inspecting response headers (Servlet 3.0+)
Collection<String> responseHeaderNames = response.getHeaderNames();
for (String name : responseHeaderNames) {
  String val = response.getHeader(name);
  out.println(name + " : " + val + "<br>");
}

Common HTTP Headers You Should Know

  • User-Agent: Identifies the client software, operating system, and browser version.
  • Accept-Encoding: Details supported compression formats (such as gzip, deflate).
  • Host: Identifies the target domain and port number being accessed.
  • Content-Type: Tells the receiving party the media type of the transmitted body data.

📺 Related HTTP & Servlets Tutorials

Deepen your understanding of HTTP request and response cycles with these tutorials from our channel:


Click here to watch in Youtube : https://www.youtube.com/watch?v=hHcvTVFx9S0

Click the below Image to Enlarge

DisplayAllHeaders Project Dir Structure

DisplayHeadersServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DisplayHeadersServlet extends HttpServlet
{

    private static final long serialVersionUID = 1L;

    public void init() throws ServletException
    {

        System.out.println("\n*******************************************\n");
        System.out.println("HelloWorld servlet init method has been called");
        System.out.println("\n*******************************************\n");

    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();
        String title = "HTTP Header Request Example";
        String docType = "<!doctype html public \"-//w3c//dtd html 4.0 "
                + "transitional//en\">\n";
        out.println(docType + "<html>\n" + "<head><title>" + title
                + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n"
                + "<h1 align=\"center\">" + title + "</h1>\n"
                + "<table width=\"100%\" border=\"1\" align=\"center\">\n"
                + "<tr bgcolor=\"#949494\">\n"
                + "<th>Header Name</th><th>Header Value(s)</th>\n" + "</tr>\n");

        Enumeration<String> headerNames = request.getHeaderNames();

        while (headerNames.hasMoreElements())
        {
            String headerName = (String) headerNames.nextElement();
            out.print("<tr><td>" + headerName + "</td>\n");
            String headerValue = request.getHeader(headerName);
            out.println("<td> " + headerValue + "</td></tr>\n");
        }
        out.println("</table>\n</body></html>");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        doGet(request, response);
    }

    public void destroy()
    {
        // do nothing.
    }
}

web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
metadata-complete="true" version="3.0">
  <display-name>ServletForm GET</display-name>
  <description>
        This is a simple web application with a source code organization
        based on the recommendations of the Application Developer's Guide.
    </description>
  <servlet>
    <servlet-name>readAllHeaders</servlet-name>
    <servlet-class>DisplayHeadersServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>readAllHeaders</servlet-name>
    <url-pattern>/readAllHeaders</url-pattern>
  </servlet-mapping>
</web-app>

index.html
<!DOCTYPE HTML><html lang="en"><head>
<meta charset="UTF-8">
<title>Order Pizza</title>
</head>
<body>
<p>
<h3>Order Pizza</H3>
<p></p>
<ul>
    <li><a href="pizza.html">Order Pizza</a></li>
</ul>
</body></html>

pizza.html
<html>
<head>
<title>Retrieving All Parameters</title>
 </head>
<body>
<h4>Order your Pizza Here</h4>
<form action="readAllHeaders" method="POST">
<b>Name</b> <input type="text" name="name"><br><br>
<b>Select the Crust:</b>
<select name = "crust">
<option value="pan">Pan</option>
<option value="thin">Thin Crust</option>
<option value="deep">Deep Crust</option>
<option value="cheese">Cheese Burst</option>
</select> <br><br>
<b>Toppings: </b><br>
<input type="checkbox" name="toppings" value="peas">Peas<br>
<input type="checkbox" name="toppings" value="paneer">Paneer<br>
<input type="checkbox" name="toppings" value="redpeppers">Red Peppers<br>
<input type="checkbox" name="toppings" value="pineapple">Pineapple<br>
<input type="checkbox" name="toppings" value="onion">Onion<br>
<input type="checkbox" name="toppings" value="tomato">Tomato<br><br>
 
<b>Select 1 FREE Appetizer</b>
<input type="radio" name="appetizer" value="Garlic Bread">Garlic Bread
<input type="radio" name="appetizer" value="Cheese Garlic Bread">Cheese Garlic Bread
<input type="radio" name="appetizer" value="Veg Soup">Veg Soup
<input type="radio" name="appetizer" value="Veg Sandwich">Veg Sandwich<br><br>
 
<b>Address</b><br>
<textarea name="address" rows=3 cols=40></textarea><br><br>
<b>Credit Card:</b><br>
<input type="radio" name="cardType" value="Visa">Visa
<input type="radio" name="cardType" value="MasterCard">MasterCard
<input type="radio" name="cardType" value="Amex">American Express
<br><br>
<b>Credit Card Number:</b> <input type="password" name="cardNum">
<b>Repeat Credit Card Number: </b><input type="password" name="cardNum"><br><br>
<input type="submit" name="submit" value="Order Pizza">
</form>
</body>
</html>

Environment Used 

JDK version :1.6.0_30
Tomcat version : 7.0.50 

To Download DisplayAllHeadersApp Project Click the below link

https://sites.google.com/site/javaee4321/servlets/DisplayAllHeadersApp.zip?attredirects=0&d=1

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Friday, 2 May 2014

    Servlets : PageAutoRefresh

    🚀 Master Java Servlets & Web Development!

    Subscribe to Ram N Java for clean, beginner-friendly coding tutorials and practical web architecture guides!

    👉 Click Here to Subscribe Now

    What is Page Auto Refresh in Java Servlets?

    In web applications displaying live statistics, stock prices, sports scores, or dynamic server clocks, you often want the browser to automatically reload the page at a fixed time interval without any user intervention.

    In Java Servlets, you can accomplish automatic page reloading on the client side using the standard HTTP response header named Refresh via response.setIntHeader().

    How the Refresh Header Works

    When the servlet sends an HTTP response containing the Refresh header, it informs the browser to wait for a specified number of seconds before re-requesting the current URL:

    // Refresh the page every 5 seconds
    response.setIntHeader("Refresh", 5);

    Every 5 seconds, the browser will automatically issue a fresh GET request to the same servlet, fetching and rendering the most up-to-date data.

    Complete Servlet Example: Live Digital Clock

    Here is a complete, beginner-friendly example of an auto-refreshing digital clock servlet:

    @WebServlet("/AutoRefreshServlet")
    public class AutoRefreshServlet extends HttpServlet {

      protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {

        // Set the refresh interval in seconds
        response.setIntHeader("Refresh", 1);

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        // Get current system time
        Calendar calendar = new GregorianCalendar();
        String am_pm = calendar.get(Calendar.AM_PM) == 0 ? "AM" : "PM";
        String currentTime = calendar.get(Calendar.HOUR) + ":" +
                             calendar.get(Calendar.MINUTE) + ":" +
                             calendar.get(Calendar.SECOND) + " " + am_pm;

        out.println("<h2>Auto Refreshing Page Demo</h2>");
        out.println("<p>Current Time: <strong>" + currentTime + "</strong></p>");
      }
    }

    Bonus: Refresh and Redirect to Another URL

    You can also use the Refresh header to pause for a few seconds before redirecting the client to a different URL using setHeader():

    // Wait 5 seconds, then redirect the user to a new destination
    response.setHeader("Refresh", "5; URL=https://www.youtube.com/@ramnjava");

    Key Best Practices

    • Choose Appropriate Intervals: Refreshing too quickly (e.g., sub-second intervals) creates unnecessary server load and bandwidth usage.
    • Set Before Writing: Always set response headers before committing the response or flushing the output stream.
    • Alternative Modern Options: While HTTP Refresh headers are fast and require zero JavaScript, modern interactive apps often use AJAX, WebSockets, or Server-Sent Events (SSE) for partial page updates.

    📺 Related HTTP & Response Handling Tutorials

    Explore more response handling and HTTP concept tutorials from our channel:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=S0Z04k6r61A

    Click the below Image to Enlarge

    PageAutoRefresh Project Dir Structure

    PageRefreshServlet.java
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class PageRefreshServlet extends HttpServlet
    {
    
        private static final long serialVersionUID = 1L;
    
        public void init() throws ServletException
        {
            System.out
                    .println("------------------------------------------------------");
            System.out.println(" Init method is called in "
                    + this.getClass().getName());
            System.out
                    .println("------------------------------------------------------");
        }
    
        // Method to handle GET method request.
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException
        {
            
            System.out.println(" doGet method is called in "
                    + this.getClass().getName());
            
            // Set refresh, autoload time as 5 seconds
            response.setIntHeader("Refresh", 5);
    
            // Set response content type
            response.setContentType("text/html");
    
            // Get current time
            Calendar calendar = new GregorianCalendar();
            String am_pm;
            int hour = calendar.get(Calendar.HOUR);
            int minute = calendar.get(Calendar.MINUTE);
            int second = calendar.get(Calendar.SECOND);
            if (calendar.get(Calendar.AM_PM) == 0)
                am_pm = "AM";
            else
                am_pm = "PM";
    
            String CT = hour + ":" + minute + ":" + second + " " + am_pm;
    
            PrintWriter out = response.getWriter();
            String title = "Auto Page Refresh using Servlet";
            String docType = "<!doctype html public \"-//w3c//dtd html 4.0 "
                    + "transitional//en\">\n";
            out.println(docType + "<html>\n" + "<head><title>" + title
                    + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n"
                    + "<h1 align=\"center\">" + title + "</h1>\n"
                    + "<p>Current Time is: " + CT + "</p>\n");
        }
    
        // Method to handle POST method request.
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException
        {
            doGet(request, response);
        }
    
        public void destroy()
        {
            System.out
                    .println("------------------------------------------------------");
            System.out.println(" destroy method is called in "
                    + this.getClass().getName());
            System.out
                    .println("------------------------------------------------------");
        }
    }
    

    web.xml
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        metadata-complete="true" version="3.0">
    
          <display-name>PageAutoRefresh</display-name>
    
          <description>
            This is a simple web application with a source code organization
            based on the recommendations of the Application Developer's Guide.
          </description>
    
           <servlet>
            <servlet-name>refresh</servlet-name>
            <servlet-class>PageRefreshServlet</servlet-class>
        </servlet>
        
        <servlet-mapping>
            <servlet-name>refresh</servlet-name>
            <url-pattern>/PageRefresh</url-pattern>
        </servlet-mapping>
    </web-app>
    

    index.html
    <!DOCTYPE HTML>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>PageRefresh</title>
    </head>
    <body>
        <li><a href="PageRefresh">PageRefresh</a></li>
    </body>
    </html>
    
    

    Environment Used 

    JDK version :1.6.0_30
    Tomcat version : 7.0.50 

    To Download PageAutoRefreshApp Project Click the below link

    https://sites.google.com/site/javaee4321/servlets/PageAutoRefreshApp.zip?attredirects=0&d=1

     See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Sunday, 16 March 2014

    View HTTP Request and Response Header - Firefox

    🚀 Master Java & Servlets with Ram N Java!

    Subscribe to get clear, beginner-friendly tutorials right when they drop.

    🔔 Subscribe to Ram N Java

    Why Inspect HTTP Headers in Web Applications?

    Whenever a browser communicates with a Java Servlet, they exchange metadata alongside the message body. This metadata is contained inside HTTP Request and Response Headers.

    Inspecting these headers is essential for debugging web applications. It allows developers to check cookies, session IDs, content encoding, cache policies, redirect status codes, and content lengths in real-time.

    Understanding Request vs. Response Headers

    HTTP headers operate in two primary directions during any client-server interaction:

    • HTTP Request Headers: Sent by the client (browser) to the server. Common headers include User-Agent, Accept, Host, and Cookie. In Servlets, you inspect these using methods on HttpServletRequest like getHeader(String name) and getHeaderNames().
    • HTTP Response Headers: Sent by the server (your Servlet) back to the browser. Common headers include Content-Type, Content-Length, Set-Cookie, and Location. In Servlets, you configure these using methods on HttpServletResponse like setHeader(String name, String value).

    How to View Headers in Firefox Developer Tools

    You do not need extra external tools to inspect HTTP traffic. Firefox includes built-in developer tools to inspect all network calls:

    1. Press F12 (or right-click anywhere on the webpage and select Inspect).
    2. Navigate to the Network tab.
    3. Trigger your Servlet request by reloading the page or submitting a form.
    4. Click on the specific request entry in the table, then open the Headers panel on the right side to examine full Request and Response header key-value pairs.

    Recommended Next Watch

    Broaden your understanding of Java web communication with these recommended tutorials:


    Click here to watch in Youtube :  https://www.youtube.com/watch?v=bZWCuWrTPY0

    To Download the Sample war file Click the below link:

    https://sites.google.com/site/javaee4321/servlets/ServletFormReadAllParam.war?attredirects=0&d=1

    Click the below Image to Enlarge
    View HTTP Request and Response Header - Firefox
    View HTTP Request and Response Header - Firefox
    View HTTP Request and Response Header - Firefox
    View HTTP Request and Response Header - Firefox
    View HTTP Request and Response Header - Firefox
    View HTTP Request and Response Header - Firefox
    View HTTP Request and Response Header - Firefox
    View HTTP Request and Response Header - Firefox




































































































    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Friday, 14 March 2014

    View HTTP Request and Response Header - web sniffer

    🚀 Master Java & Servlets with Ram N Java!

    Subscribe to get clear, beginner-friendly tutorials right when they drop.

    🔔 Subscribe to Ram N Java

    What is a Web Sniffer?

    When working with Java Servlets and web servers, raw communication happens over HTTP. A Web Sniffer is an online utility or network analysis tool that captures and displays the exact HTTP exchange between a web client and a server.

    Instead of relying solely on browser interpretations, a web sniffer shows the raw, unadorned HTTP request sent to a destination and the exact HTTP response headers returned by the server.

    Why Use Web Sniffer Tools for Servlets?

    Inspecting your Servlets through a web sniffer provides several practical advantages for web developers:

    • Verify Server Headers: Ensure custom headers set inside your Servlet via response.setHeader() are successfully received.
    • Validate Content Types: Confirm that the Content-Type and character encoding match what the client expects (e.g., text/html; charset=UTF-8).
    • Diagnose Redirects and Status Codes: Check status codes like 200 OK, 302 Found, 404 Not Found, or 500 Internal Server Error without browser caching interference.
    • Inspect Cookie Directives: Observe incoming Cookie headers and server-issued Set-Cookie directives in raw text format.

    How to Analyze Headers Using Web Sniffer

    1. Enter the target Servlet URL or web endpoint into the Web Sniffer tool interface.
    2. Select the appropriate HTTP request method (such as GET or POST) and submit the request.
    3. Examine the top section to see the full set of generated Request Headers sent by the client.
    4. Review the lower section to inspect the full Response Headers and body returned directly by your web container.

    Recommended Next Watch

    Enhance your HTTP and Java Servlet troubleshooting knowledge with these tutorials:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=Q_8FRnYRPCM

    Click the below Image to Enlarge
    View HTTP Request and Response Header - web sniffer
    View HTTP Request and Response Header - web sniffer
    View HTTP Request and Response Header - web sniffer






































    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • HTTP - Responses

    Enjoying this guide? Join our developer community!

    Subscribe to Ram N Java on YouTube

    Anatomy of an HTTP Response: Structure, Status Codes, and Headers

    Whenever a client (such as your browser or an API consumer) sends an HTTP request to a server, the server processes that request and sends back an HTTP Response. Understanding the structure and components of this response is crucial for developing, troubleshooting, and testing web applications.

    The Four Core Components of an HTTP Response

    Every standard HTTP response message consists of four distinct sections:

    1. Status Line: The initial line providing the protocol version, status code, and reason phrase.
    2. Header Fields: Key-value metadata providing details about the server, response, or payload.
    3. An Empty / Blank Line: A required blank line that marks the boundary where headers end.
    4. Message Body (Optional): The actual delivered content (such as an HTML document, JSON payload, or image).

    Understanding the Status Line

    Consider a standard response line example:

    HTTP/1.1 200 OK

    The status line contains three essential elements:

    • HTTP Version (HTTP/1.1): The protocol version implemented by the server.
    • Status Code (200): A 3-digit numeric code indicating the outcome of the request.
    • Reason Phrase (OK): A short, human-readable text explanation accompanying the code.

    The 5 HTTP Status Code Categories

    HTTP status codes are categorized into five ranges based on the first digit:

    • 1xx (Informational): The request has been received and the server is continuing the process.
    • 2xx (Success): The action was successfully received, understood, and accepted (e.g., 200 OK).
    • 3xx (Redirection): Further action or a different URL is required to complete the request.
    • 4xx (Client Error): The request contains bad syntax or refers to a missing resource (e.g., 404 Not Found).
    • 5xx (Server Error): The server failed to fulfill an apparently valid request due to internal issues (e.g., 500 Internal Server Error).

    Types of Response Header Fields

    Headers deliver metadata alongside the payload and fall into three main types:

    • Response Headers: Information specifically about the server and the response itself (e.g., Server, Age).
    • Entity Headers: Metadata describing the message body content, such as Content-Type and Content-Length.
    • General Headers: Headers applicable across both requests and responses, like Date and Connection.

    Click here to watch in Youtube : https://www.youtube.com/watch?v=B6O9a3TaM8M

    Click the below Image to Enlarge
    HTTP - Responses
    HTTP - Responses
    HTTP - Responses


    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Older Posts Home

    Tutorials