Checking if a URL Exists in Java
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.url;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
public class UrlChecker {
|
||||
|
||||
public int getResponseCodeForURL(String address) throws IOException {
|
||||
return getResponseCodeForURLUsing(address, "GET");
|
||||
}
|
||||
|
||||
public int getResponseCodeForURLUsingHead(String address) throws IOException {
|
||||
return getResponseCodeForURLUsing(address, "HEAD");
|
||||
}
|
||||
|
||||
private int getResponseCodeForURLUsing(String address, String method) throws IOException {
|
||||
HttpURLConnection.setFollowRedirects(false); // Set follow redirects to false
|
||||
final URL url = new URL(address);
|
||||
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
|
||||
huc.setRequestMethod(method);
|
||||
return huc.getResponseCode();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.url;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class UrlCheckerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenValidUrl_WhenUsingHEAD_ThenReturn200() throws IOException {
|
||||
UrlChecker tester = new UrlChecker();
|
||||
int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com");
|
||||
assertEquals(200, responseCode);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidIUrl_WhenUsingHEAD_ThenReturn404() throws IOException {
|
||||
UrlChecker tester = new UrlChecker();
|
||||
int responseCode = tester.getResponseCodeForURLUsingHead("http://www.example.com/unkownurl");
|
||||
assertEquals(404, responseCode);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidUrl_WhenUsingGET_ThenReturn200() throws IOException {
|
||||
UrlChecker tester = new UrlChecker();
|
||||
int responseCode = tester.getResponseCodeForURL("http://www.example.com");
|
||||
assertEquals(200, responseCode);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidIUrl_WhenUsingGET_ThenReturn404() throws IOException {
|
||||
UrlChecker tester = new UrlChecker();
|
||||
int responseCode = tester.getResponseCodeForURL("http://www.example.com/unkownurl");
|
||||
assertEquals(404, responseCode);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user