乐闻世界logo
搜索文章和话题

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

1个答案

1

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

  1. Create URL Object First, convert the string URL address into a URL object.

    java
    URL url = new URL("http://example.com");
  2. Open Connection Use the openConnection() method of the URL object to create an HttpURLConnection object.

    java
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  3. Set Request Method You can set the HTTP request method (GET, POST, etc.), with GET being the default.

    java
    connection.setRequestMethod("GET");
  4. Connect to Server Call the connect() method to establish a connection with the server.

    java
    connection.connect();
  5. Get Response Code Use the getResponseCode() method to obtain the HTTP response status code.

    java
    int responseCode = connection.getResponseCode(); System.out.println("HTTP Response Code: " + responseCode);
  6. Close Connection Close the connection after completion.

    java
    connection.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:

  1. Create HttpClient Object Create a default client instance using the HttpClients class.

    java
    CloseableHttpClient httpClient = HttpClients.createDefault();
  2. Create HttpGet Object Create an HttpGet object to set the target URL.

    java
    HttpGet request = new HttpGet("http://example.com");
  3. Execute Request Execute the request using the execute() method, which returns a CloseableHttpResponse object.

    java
    CloseableHttpResponse response = httpClient.execute(request);
  4. Get Response Code Retrieve the status line from the response object and then get the status code.

    java
    int responseCode = response.getStatusLine().getStatusCode(); System.out.println("HTTP Response Code: " + responseCode);
  5. Close Resources Finally, close the HttpResponse and HttpClient.

    java
    response.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.

2024年8月5日 01:09 回复

你的答案