Understanding HTTP Through a Simple Java Story: From Sessions to Web Requests
This article explains the purpose and structure of the HTTP protocol by using a narrative about two developers building a String utility class and a card validator, then mapping their method calls to the three steps of a web request, complete with code examples and protocol details.
Introduction
HTTP is the foundation of web development, yet many developers only know it superficially. Concepts such as session handling are actually built on the HTTP Cookie header. This article explains what HTTP does, using everyday development examples.
Story: A Simple Utility
Two developers, A and B, are tasked with creating a StringUtils class that provides isNull and isEmpty methods.
/**
* Utility class
*/
public abstract class StringUtils {
public static boolean isNull(String s) {
return s == null;
}
public static boolean isEmpty(String s) {
return isNull(s) || s.length() == 0;
}
}Developer B quickly implements the class.
Using the Utility in a Card Validator
Developer A writes a validator that checks an ID number by calling the utility methods.
/**
* ID card validator
*/
public class CardNumberValidator {
/**
* Validate ID number (simplified)
*/
public boolean valid(String cardNumber) {
if (StringUtils.isNull(cardNumber)) {
throw new NullPointerException("cardNumber is null!");
} else if (StringUtils.isEmpty(cardNumber)) {
throw new IllegalArgumentException("cardNumber is empty!");
} else if (cardNumber.length() == 18) {
return true;
} else {
throw new IllegalArgumentException("the length of cardNumber must be 18!");
}
}
}Test Client
/**
* Client
*/
public class Client {
/**
* Main method
*/
public static void main(String[] args) {
CardNumberValidator validator = new CardNumberValidator();
String cardNumber = "433182198803211232";
if (validator.valid(cardNumber)) {
System.out.println(cardNumber + "是一个有效的身份证号!");
} else {
System.out.println(cardNumber + "是一个无效的身份证号!");
}
}
}The program prints a successful validation message.
433182198803211232是一个有效的身份证号!Story Analysis and HTTP Analogy
The three steps of the method call—locating the method, sending parameters, and receiving a result—mirror the three phases of a web request: locating a resource via URL, sending a request with headers and body, and receiving a response with status and data.
Finding Resources: URLs
A URL identifies a resource using the format
protocol://hostname[:port]/path/[;parameters][?query]#fragment.
Headers and Data Parsing
Headers convey metadata such as cookies, user agents, and content types. The request and response examples below illustrate typical header usage.
GET http://www.cnblogs.com/mvc/Follow/GetFollowStatus.aspx HTTP/1.1
Host: www.cnblogs.com
User-Agent: Mozilla/5.0 ...
Accept: text/plain, */*; q=0.01
Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
Referer: http://www.cnblogs.com
Cookie: _ga=...; .CNBlogsCookie=...
Connection: keep-alive HTTP/1.1 200 OK
Date: Fri, 17 Apr 2015 10:18:06 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 128
Connection: keep-alive
Cache-Control: private
X-UA-Compatible: IE=10
<a href="javascript:void(0);" onclick="cnblogs.UserManager.FollowBlogger('...')">+加关注</a>HTTP in Java Web Development
Java servlet APIs expose the HTTP request and response through HttpServletRequest and HttpServletResponse interfaces, which define methods for accessing headers, parameters, session IDs, and status codes.
public interface HttpServletRequest extends ServletRequest {
String getAuthType();
Cookie[] getCookies();
long getDateHeader(String name);
String getHeader(String name);
Enumeration getHeaders(String name);
Enumeration getHeaderNames();
int getIntHeader(String name);
String getMethod();
String getPathInfo();
String getQueryString();
String getRemoteUser();
boolean isUserInRole(String role);
HttpSession getSession();
// ... other methods ...
}
public interface HttpServletResponse extends ServletResponse {
void addCookie(Cookie cookie);
boolean containsHeader(String name);
String encodeURL(String url);
void sendError(int sc, String msg) throws IOException;
void sendRedirect(String location) throws IOException;
void setStatus(int sc);
// ... other methods ...
}These interfaces are designed according to the HTTP specification, and they evolve when the protocol changes.
Conclusion
Understanding HTTP through everyday coding scenarios helps developers grasp its purpose and essential components without memorizing every header. Remember: bugs destroy quickly, repetition destroys forever—refactor early.
About 21CTO
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.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
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.
