Analyze the use cases and solutions of 4xx status codes in HTTP protocol

WBOY
Release: 2023-12-26 09:00:58
Original
788 people have browsed it

Analyze the use cases and solutions of 4xx status codes in HTTP protocol

Explore the application scenarios and solutions of 4xx status codes in the HTTP protocol

Introduction:
In Web development, the HTTP protocol plays a very important role. It defines the rules and conventions for communication between clients and servers. Among them, the status code is an identifier used by the server to convey the request processing status to the client. In the HTTP protocol, 4xx status codes indicate that an error occurred on the client side. This article will explore the application scenarios and solutions of 4xx status codes, and provide relevant code examples.

1. Application scenarios:

  1. 400 Bad Request: Indicates that the client submitted an invalid request.

    • Scenario 1: The request parameters are illegal. For example, required parameters are missing, parameter values are in incorrect format, etc.
    • Scenario 2: The request body format is incorrect. For example, the request body should be in JSON format, but what is actually submitted is in XML format.
  2. 401 Unauthorized: Indicates that the client is not authenticated or the authentication fails.

    • Scenario 1: Missing authentication credentials. For example, the request needs to carry Token or Cookie, but the client does not provide it.
    • Scenario 2: Authentication failed. For example, the provided Token or Cookie has expired or is invalid.
  3. 403 Forbidden: Indicates that the server rejected the request.

    • Scenario 1: The client does not have permission to access specific resources. For example, trying to access restricted API interfaces or files.
    • Scenario 2: Access frequency is too high. For example, the server is limited to 100 requests per minute, and the client exceeds the limit.
  4. 404 Not Found: Indicates that the resource requested by the client does not exist.

    • Scenario 1: The requested URL path does not exist. For example, an incorrect URL address was entered.
    • Scenario 2: The requested resource has been deleted or moved. For example, access a deleted article.
##2. Solution:

  1. 400 Bad Request solution:

      Use parameter calibration Verification tool library. For example, verify the validity of request parameters, such as whether the parameters are empty, whether the length meets the requirements, etc.
    • Use regular expressions to verify the request body format. For example, regular expressions are used to match whether the request body meets specific format requirements.
    Code example:

    @RequestMapping(value = "/example", method = RequestMethod.POST) public ResponseEntity example(@RequestBody ExampleRequest request) { if (StringUtils.isBlank(request.getName())) { return ResponseEntity.badRequest().body("Name cannot be blank"); } if (!request.getAge().matches("\d+")) { return ResponseEntity.badRequest().body("Age must be a number"); } // 处理正常流程 return ResponseEntity.ok("Success"); }
    Copy after login

  2. 401 Unauthorized solution:

      Provide an authentication interface and return Token or Cookie. The client needs to add Token or Cookie to each request.
    • Use interceptors to intercept interfaces that require authentication. Check whether the request header carries a valid Token or Cookie.
    Code sample:

    public class AuthInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token = request.getHeader("Token"); if (StringUtils.isBlank(token)) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getWriter().println("Authentication failed"); return false; } // 验证Token的合法性 // ... return true; } }
    Copy after login

  3. 403 Forbidden solution:

      Permission control for each resource. Only users with sufficient permissions have access.
    • Use the current limiting tool to limit the request frequency. When the request frequency exceeds the limit, a 403 Forbidden status code is returned.
    Code example:

    @RequestMapping(value = "/admin", method = RequestMethod.GET) @RequiresRoles("admin") public ResponseEntity admin() { // 处理业务逻辑 }
    Copy after login

  4. 404 Not Found Solution:

      Return when the requested URL path does not exist Custom 404 page.
    • Record logs and notify relevant personnel. If the requested resource has been deleted or moved, notify the client and provide the correct URL address.
    Code example:

    @RequestMapping(value = "/{id}", method = RequestMethod.GET) public ResponseEntity getResource(@PathVariable("id") String id) { // 查询资源 // 若资源不存在,则返回404 Not Found状态码 if (resource == null) { return ResponseEntity.notFound().build(); } // 处理正常流程 return ResponseEntity.ok("Success"); }
    Copy after login

Conclusion:

By exploring the application scenarios and solutions of 4xx status codes, we can better understand The meaning of 4xx status codes in the HTTP protocol and the ability to handle these error conditions more effectively during development. Reasonable use of 4xx status codes can provide a better user experience for the client and is also helpful for troubleshooting and repair.

(Note: The above code examples are examples of the Java Spring MVC framework. The implementation methods of other programming languages and frameworks may be different, but the ideas are similar)

The above is the detailed content of Analyze the use cases and solutions of 4xx status codes in HTTP protocol. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!