Explain Codes LogoExplain Codes Logo

How to get HTTP response code for a URL in Java?

java
http-requests
http-response-codes
httpclient
Alex KataevbyAlex Kataev·Feb 18, 2025
TLDR

Fetch the HTTP status code with Java's HttpURLConnection. Initialize one from a URL and invoke getResponseCode():

URL url = new URL("http://example.com"); int code = ((HttpURLConnection)url.openConnection()).getResponseCode();

This code snippet enables easy retrieval of the status code for any given URL.

HttpURLConnection: Setting up and using it

HttpURLConnection is a member of the java.net package, a crucial package for network operations. Although it's fairly simple to get the response code, remember to handle exceptions. To ensure robustness of your code, wrap it in try-catch blocks.

Establishing connectivity

Before obtaining the response code, set up the HttpURLConnection:

URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); // GET is already default. But hey, we're just being sure! connection.connect();

Handling unpredicted situations

Handle exceptions properly when dealing with network operations:

try { URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int responseCode = connection.getResponseCode(); System.out.println("Response Code: " + responseCode); } catch (IOException e) { e.printStackTrace(); // Time to play detective Sherlock here! }

Ensuring clean-up post operation

After finishing the operation, close the connection to release network resources:

connection.disconnect(); // Bye bye connection!

HttpClient: An alternate approach

HttpClient from Apache HttpComponents comes with enhanced abilities for handling HTTP requests and responses. It becomes handy when you delve into advanced features like handling timeouts or custom request headers.

Kickstarting HttpClient

To start with HttpClient, create an instance and make a request:

CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet request = new HttpGet("http://example.com"); CloseableHttpResponse response = httpClient.execute(request); // Action time!

Fetching the response

Fetch comprehensive HTTP response info, including the status code:

int statusCode = response.getStatusLine().getStatusCode(); // The all-important code!

Dealing with exceptions

HttpClient requires good exception handling, with IOException and ClientProtocolException as potential blockers:

try { response = httpClient.execute(request); statusCode = response.getStatusLine().getStatusCode(); } catch (IOException e) { e.printStackTrace(); // Well, you can't predict everything right! } finally { response.close(); // See you next time connection. }

Under the hood

Think of obtaining the HTTP response code as sonar pings sent to detect submarines:

📡 --> Ping! --> 🚢 (URL) \ / `--- 🔗 Code ---`

HTTP Response Codes Illustrated:

  • 200 OK : 🟢 (All is well)
  • 404 Not Found : 🔴 (Oops, seems like a ghost URL!)
  • 500 Server Error : 🟠 (Warning! Server needs help)
Call to actionHTTP CodeGraphic
📡 --> 🚢200 All good
📡 -->404 Boo! Ghost
📡 --> 🚢 💥500🟠 SOS!

Fine-tuning: Tips and Tricks

Efficient resource handling

Utilize try-with-resources when dealing with InputStream or BufferedReader for better management:

try (BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream()))) { // Read and conquer! }

Interpretation of success

A good practice is to verify successful request by comparing the response code to 200:

if (responseCode == HttpURLConnection.HTTP_OK) { // Party time! }

Casting of connection

After calling url.openConnection(), cast the returned value to HttpURLConnection assuming you're sure of the URL's protocol:

HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // Assumptions can be dangerous!

Greater power with HttpClient

In scenarios where HttpURLConnection falls short, HttpClient offers more flexible solutions for sending HTTP requests and getting responses.

Parting words

With practice, mastery is inevitable. Cast your vote if you found my solution helpful! Happy coding, you titan of a programmer!👨‍💻👩‍💻