Understanding HTTP Protocol and Using Java Servlets to Set Response Headers
This article explains the fundamentals of the HTTP protocol, compares HTTP/1.0 and HTTP/1.1, details request and response structures, and demonstrates how to control browser behavior with various response headers using Java servlet examples.
What is HTTP Protocol
HTTP (Hypertext Transfer Protocol) is an application‑layer protocol of TCP/IP that defines the data exchange format between web browsers and web servers. After a client connects to a server, it must follow a specific communication format defined by HTTP to request resources.
HTTP Protocol Versions
HTTP/1.0 and HTTP/1.1
Differences Between HTTP/1.0 and HTTP/1.1
In HTTP/1.0 a client can obtain only one resource per connection, while HTTP/1.1 allows multiple resources to be fetched over a single persistent connection.
HTTP Request
4.1 Content of an HTTP Request
A complete HTTP request consists of a request line, several header fields, and an optional entity body.
Example:
4.2 Request Line Details
The request line contains the method (GET, POST, etc.), the URL, and the HTTP version. GET appends parameters to the URL (limited to ~1 KB), while POST sends data in the request body without size limitation.
4.3 Header Fields
Common request headers include Accept, Accept‑Charset, Accept‑Encoding, Accept‑Language, Host, If‑Modified‑Since, Referer, and Connection.
1 Accept: application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
2 Referer: http://localhost:8080/JavaWebDemoProject/Web/2.jsp
3 Accept-Language: zh-CN
4 User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)
5 Accept-Encoding: gzip, deflate
6 Host: localhost:8080
7 Connection: Keep-AliveHTTP Response
5.1 Content of an HTTP Response
An HTTP response consists of a status line, header fields, and an optional entity body.
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=ISO-8859-1
Content-Length: 105
Date: Tue, 27 May 2014 16:23:28 GMT
<html>
<head><title>Hello World JSP</title></head>
<body>Hello World!</body>
</html>5.2 Status Line Details
The status line format is HTTP-Version SP Status-Code SP Reason-Phrase CRLF . Status codes are three‑digit numbers grouped into five classes (1xx–5xx).
5.3 Common Response Headers
Typical response headers include Location, Server, Content‑Encoding, Content‑Length, Content‑Language, Content‑Type, Refresh, Content‑Disposition, Transfer‑Encoding, Expires, Cache‑Control, and Pragma.
Setting Response Headers on the Server
6.1 Redirect with Location Header
package gacl.http.study;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo01 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setStatus(302); // set status code
// set Location header to redirect the browser
response.setHeader("Location", "/JavaWeb_HttpProtocol_Study_20140528/1.jsp");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}When accessing the servlet, the server returns a 302 status and a Location header, causing the browser to redirect to the specified JSP page.
6.2 Content‑Encoding Header for GZIP Compression
package gacl.http.study;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo02 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data = "abcdabcd..."; // long string
System.out.println("Original size: " + data.getBytes().length);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
GZIPOutputStream gout = new GZIPOutputStream(bout);
gout.write(data.getBytes());
gout.close();
byte[] g = bout.toByteArray();
response.setHeader("Content-Encoding", "gzip");
response.setHeader("Content-Length", g.length + "");
response.getOutputStream().write(g);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}6.3 Setting Content‑Type Header
package gacl.http.study;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo03 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("content-type", "image/jpeg");
InputStream in = this.getServletContext().getResourceAsStream("/img/WP_20131005_002.jpg");
byte[] buffer = new byte[1024];
int len = 0;
OutputStream out = response.getOutputStream();
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}6.4 Refresh Header for Automatic Redirection
package gacl.http.study;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo04 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// redirect after 3 seconds to Baidu
response.setHeader("refresh", "3;url='http://www.baidu.com'");
response.getWriter().write("gacl");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}6.5 Content‑Disposition Header for File Download
package gacl.http.study;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo05 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("content-disposition", "attachment;filename=xxx.jpg");
InputStream in = this.getServletContext().getResourceAsStream("/img/1.jpg");
byte[] buffer = new byte[1024];
int len = 0;
OutputStream out = response.getOutputStream();
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}The article concludes with screenshots of the servlet outputs, demonstrating how different response headers affect browser behavior such as redirection, compression, content type rendering, periodic refresh, and file download.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
