How to get HTTP response code for a URL in Java?
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 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: UsingCreate URL ObjectFirst, convert the string URL address into a object.Open ConnectionUse the method of the object to create an object.Set Request MethodYou can set the HTTP request method (GET, POST, etc.), with GET being the default.Connect to ServerCall the method to establish a connection with the server.Get Response CodeUse the method to obtain the HTTP response status code.Close ConnectionClose the connection after completion.Method Two: Using Apache HttpClientFirst, add the Apache HttpClient library dependency to your project. For Maven, add the following to your :Next, the steps to obtain the HTTP response code using Apache HttpClient:Create HttpClient ObjectCreate a default client instance using the class.Create HttpGet ObjectCreate an object to set the target URL.Execute RequestExecute the request using the method, which returns a object.Get Response CodeRetrieve the status line from the response object and then get the status code.Close ResourcesFinally, close the and .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.