Home > Java > javaTutorial > body text

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

Barbara Streisand
Release: 2024-11-10 08:54:03
Original
370 people have browsed it

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!

source:dev.to
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 Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template