Home Java javaTutorial Guide to HTTP Codes in Java: How to understand what the server wants from you?

Guide to HTTP Codes in Java: How to understand what the server wants from you?

Nov 10, 2024 am 08:54 AM

In the world of HTTP codes, every server response is like a message from the other end of the universe. You sent a request, and now this mysterious code appears on the screen. What does it mean? How should we understand it? Let's figure out how to catch signals from the server and not fall into a trap.

Why do they even answer us with codes?

The server is like a good old professor. He won't write long letters every time. It uses HTTP codes, or three-digit signals, in its responses to help you (and other developers) understand what's going on. They are divided into five categories, like respected age groups, from the wise informational (1xx) to the capricious erroneous (4xx and 5xx).

Here are our main characters:

  • 1xx: The server, thoughtfully sipping coffee, says: “Yes, yes, I’m working, wait...”
  • 2xx: Everything is cool, the request is completed, the server is happy.
  • 3xx: "Oh, listen, you went the wrong way. Let me redirect you!"
  • 4xx: The server is indignant: “You misunderstood me, what do you want?”
  • 5xx: Oh, it seems the server dropped something important and got confused.

How can you tell if the server is happy? Codes 2xx
The server, like any introvert, is simply happy if you did everything right. Here are his signals of approval:

  • 200 OK - “Everything went like clockwork!” The request has been processed, you can rejoice.
  • 201 Created - “Something new has been created, catch it!” As a bonus, this could be a new entry in the database.
  • 204 No Content - "Everything is ready, but I have nothing to show." For example, you deleted something and there is nothing left to show there.

Путеводитель по HTTP-кодам в Java: Как понять, что сервер от тебя хочет?

Example in Java: How to get this magical "OK"?

HttpURLConnection connection = (HttpURLConnection) new URL("https://easy.java.com/data").openConnection();
connection.setRequestMethod("GET");

if (connection.getResponseCode() == 200) {
    System.out.println("Сервер сказал ОК! Тянем данные...");
}

Copy after login
Copy after login

What if the server is not happy? Codes 4xx

There may already be problems here, like if you accidentally **opened the wrong door**.

Путеводитель по HTTP-кодам в Java: Как понять, что сервер от тебя хочет?

  • 400 Bad Request - “You clearly did something wrong in your request.”
  • 401 Unauthorized - "Who are you? I don't know you." Looks like you need a password!
  • 402 Payment Required. This code was reserved for paid access to certain resources, but is almost never used. If it were used, it would sound like: “Pay the bill first, then gain access!” Perhaps the server would stand at the entrance with a cash register.
  • 403 Forbidden - "Hey, even with the password you can't get in here." Apparently, the access is wrong.
  • 404 Not Found - "It was somewhere... but it disappeared somewhere." This code is simply classic.
  • 409 Conflict - "You and someone else want the same thing. Who will win?"
  • Example: handling errors when the server grumbles
int responseCode = connection.getResponseCode();

if (responseCode == 404) {
    System.out.println("Сервер говорит, что ничего не нашел.");
} else if (responseCode == 401) {
    System.out.println("Ой, кажется, сюда нужен пароль.");
}

Copy after login
Copy after login

When the server hosted a rock concert: codes 5xx

And then the server can’t stand it. He wanted to work, but somewhere something clearly went wrong.

  • 500 Internal Server Error - Imagine that the server is a rock star who suddenly loses a note in the middle of a concert and is forced to admit defeat: “Something went wrong!” This is the standard reaction of the server when it itself does not understand what happened. In the code it often looks like “General error, something didn’t work”, and in the logs you can see something like “Unknown error occurred”.
  • 501 Not Implemented - This code means that the server has no idea how to process the current request. You can imagine him as an IT specialist who is asked to fix the faucet in the kitchen. He stands with the key, looks at the tap and says: “This is not my specialty!” Most often this occurs if the client makes a request that the server does not support.
  • 502 Bad Gateway Here an intermediary server (gateway or proxy) tries to contact another server, but it responded with something incomprehensible or did not respond at all
  • 503 Service Unavailable - “Oh, I can’t right now, give me five minutes.” Either the service is down, or the server is full. If the server could take days off, this would be his favorite code.
  • 504 Gateway Timeout This code means that the server did not wait for a response from another server that should have responded to the request. Imagine a server waiting for a response that never came. As a result, the server says to the client: “Well, I waited and waited, but got nothing.”

Путеводитель по HTTP-кодам в Java: Как понять, что сервер от тебя хочет?

Using RestTemplate: how to communicate with a server in Spring

When you work with Spring, you have a RestTemplate and WebClient for requests. They allow you to catch server responses like a real fisherman.

RestTemplate: catching the server response

HttpURLConnection connection = (HttpURLConnection) new URL("https://easy.java.com/data").openConnection();
connection.setRequestMethod("GET");

if (connection.getResponseCode() == 200) {
    System.out.println("Сервер сказал ОК! Тянем данные...");
}

Copy after login
Copy after login

WebClient for asynchrony lovers

WebClient is a tool for those who are not afraid to work in the “waiting, but not right away” style. It’s as if you’re saying: “Server, do what you can, and I’ll wait for now.”

int responseCode = connection.getResponseCode();

if (responseCode == 404) {
    System.out.println("Сервер говорит, что ничего не нашел.");
} else if (responseCode == 401) {
    System.out.println("Ой, кажется, сюда нужен пароль.");
}

Copy after login
Copy after login

Adviсe

Check the timeouts - sometimes the server freezes, and you should be on time for lunch. Set the waiting time.
Don't forget about logging - every code is important! Log the answers and you will always be able to understand what went wrong.
Work with 4xx and 5xx - learn from mistakes. The better you handle such responses, the more robust your application will be.

Conclusion

The server is a capricious creature, and every time you receive a code from it, it’s like you’re solving a rebus. But, knowing the basic codes and their meaning, you can quickly understand what is required of you!

Remember: HTTP codes are the language of communication between your Java code and the server. Know how to read it, and the server will always be happy.

The above is the detailed content of Guide to HTTP Codes in Java: How to understand what the server wants from you?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles