Solution
Okay I found 1 solution on Stackoverflow after a little more searching but I hope to do it with no extra libraries. http://stackoverflow.com/questions/2230676/how-to-check-for-a-valid-url-in-java/2230770#2230770
My problem:
First of hopefully this is not a duplicate, but I could not find the right answer(right away). I would like to validate that an URI(http) is valid in Java. I came up with the following tests but I can't get them to pass. First I used getPort()
, but then http://www.google.nl
will return -1 on getPort()
. This are the test I want to have passed
Test:
@Test
public void testURI_Isvalid() throws Exception {
assertFalse(HttpUtils.validateHTTP_URI("ttp://localhost:8080"));
assertFalse(HttpUtils.validateHTTP_URI("ftp://localhost:8080"));
assertFalse(HttpUtils.validateHTTP_URI("http://localhost:8a80"));
assertTrue(HttpUtils.validateHTTP_URI("http://localhost:8080"));
final String justWrong =
"/schedule/get?uri=http://localhost:8080&time=1000000";
assertFalse(HttpUtils.validateHTTP_URI(justWrong));
assertTrue(HttpUtils.validateHTTP_URI("http://www.google.nl"));
}
This is what I came up with after I removed the getPort()
part but this does not pass all my unit tests.
Production code:
public static boolean validateHTTP_URI(String uri) {
final URI u;
try {
u = URI.create(uri);
} catch (Exception e1) {
return false;
}
return "http".equals(u.getScheme());
}
This is the first test that is failing because I am no longer validating the getPort() part. Hopefully somebody can help me out. I think I am not using the right class to validate URLs?
P.S:
I don't want to connect to the server to validate the URI is correct. At least not yet in this step. I only want to validate scheme.