In Java, obtaining the HTTP response code for a URL can be achieved through multiple methods, with the most common approach being the use of the HttpURLConnection class from Java's standard library or third-party libraries such as Apache HttpClient. Below, I will detail the implementation steps for both methods.
Method One: Using HttpURLConnection
-
Create URL Object First, convert the string URL address into a
URLobject.javaURL url = new URL("http://example.com"); -
Open Connection Use the
openConnection()method of theURLobject to create anHttpURLConnectionobject.javaHttpURLConnection connection = (HttpURLConnection) url.openConnection(); -
Set Request Method You can set the HTTP request method (GET, POST, etc.), with GET being the default.
javaconnection.setRequestMethod("GET"); -
Connect to Server Call the
connect()method to establish a connection with the server.javaconnection.connect(); -
Get Response Code Use the
getResponseCode()method to obtain the HTTP response status code.javaint responseCode = connection.getResponseCode(); System.out.println("HTTP Response Code: " + responseCode); -
Close Connection Close the connection after completion.
javaconnection.disconnect();
Method Two: Using Apache HttpClient
First, add the Apache HttpClient library dependency to your project. For Maven, add the following to your pom.xml:
xml<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency>
Next, the steps to obtain the HTTP response code using Apache HttpClient:
-
Create HttpClient Object Create a default client instance using the
HttpClientsclass.javaCloseableHttpClient httpClient = HttpClients.createDefault(); -
Create HttpGet Object Create an
HttpGetobject to set the target URL.javaHttpGet request = new HttpGet("http://example.com"); -
Execute Request Execute the request using the
execute()method, which returns aCloseableHttpResponseobject.javaCloseableHttpResponse response = httpClient.execute(request); -
Get Response Code Retrieve the status line from the response object and then get the status code.
javaint responseCode = response.getStatusLine().getStatusCode(); System.out.println("HTTP Response Code: " + responseCode); -
Close Resources Finally, close the
HttpResponseandHttpClient.javaresponse.close(); httpClient.close();
The above are the two common methods for obtaining the HTTP response code for a URL in Java. Both methods are practical, and the choice depends on personal or team preference and project requirements.